xref: /llvm-project/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp (revision d85b22ed5dbb794835fd4b5166d5bb79ad9e09f2)
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/TargetParser/Host.h"
15 #include "llvm/TargetParser/Triple.h"
16 #include "gtest/gtest.h"
17 
18 namespace clang {
19 namespace ast_matchers {
20 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
192 TEST_P(ASTMatchersTest, ExportDecl) {
193   if (!GetParam().isCXX20OrLater()) {
194     return;
195   }
196   const std::string moduleHeader = "module;export module ast_matcher_test;";
197   EXPECT_TRUE(matches(moduleHeader + "export void foo();",
198                       exportDecl(has(functionDecl()))));
199   EXPECT_TRUE(matches(moduleHeader + "export { void foo(); int v; }",
200                       exportDecl(has(functionDecl()))));
201   EXPECT_TRUE(matches(moduleHeader + "export { void foo(); int v; }",
202                       exportDecl(has(varDecl()))));
203   EXPECT_TRUE(matches(moduleHeader + "export namespace aa { void foo(); }",
204                       exportDecl(has(namespaceDecl()))));
205 }
206 
207 TEST_P(ASTMatchersTest, ValueDecl) {
208   if (!GetParam().isCXX()) {
209     // FIXME: Fix this test in non-C++ language modes.
210     return;
211   }
212   EXPECT_TRUE(matches("enum EnumType { EnumValue };",
213                       valueDecl(hasType(asString("enum EnumType")))));
214   EXPECT_TRUE(matches("void FunctionDecl();",
215                       valueDecl(hasType(asString("void (void)")))));
216 }
217 
218 TEST_P(ASTMatchersTest, FriendDecl) {
219   if (!GetParam().isCXX()) {
220     return;
221   }
222   EXPECT_TRUE(matches("class Y { friend class X; };",
223                       friendDecl(hasType(asString("class X")))));
224   EXPECT_TRUE(matches("class Y { friend class X; };",
225                       friendDecl(hasType(recordDecl(hasName("X"))))));
226 
227   EXPECT_TRUE(matches("class Y { friend void f(); };",
228                       functionDecl(hasName("f"), hasParent(friendDecl()))));
229 }
230 
231 TEST_P(ASTMatchersTest, EnumDecl_DoesNotMatchClasses) {
232   if (!GetParam().isCXX()) {
233     return;
234   }
235   EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
236 }
237 
238 TEST_P(ASTMatchersTest, EnumDecl_MatchesEnums) {
239   if (!GetParam().isCXX()) {
240     // FIXME: Fix this test in non-C++ language modes.
241     return;
242   }
243   EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
244 }
245 
246 TEST_P(ASTMatchersTest, EnumConstantDecl) {
247   if (!GetParam().isCXX()) {
248     // FIXME: Fix this test in non-C++ language modes.
249     return;
250   }
251   DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
252   EXPECT_TRUE(matches("enum X{ A };", Matcher));
253   EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
254   EXPECT_TRUE(notMatches("enum X {};", Matcher));
255 }
256 
257 TEST_P(ASTMatchersTest, TagDecl) {
258   if (!GetParam().isCXX()) {
259     // FIXME: Fix this test in non-C++ language modes.
260     return;
261   }
262   EXPECT_TRUE(matches("struct X {};", tagDecl(hasName("X"))));
263   EXPECT_TRUE(matches("union U {};", tagDecl(hasName("U"))));
264   EXPECT_TRUE(matches("enum E {};", tagDecl(hasName("E"))));
265 }
266 
267 TEST_P(ASTMatchersTest, TagDecl_CXX) {
268   if (!GetParam().isCXX()) {
269     return;
270   }
271   EXPECT_TRUE(matches("class C {};", tagDecl(hasName("C"))));
272 }
273 
274 TEST_P(ASTMatchersTest, UnresolvedLookupExpr) {
275   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
276     // FIXME: Fix this test to work with delayed template parsing.
277     return;
278   }
279 
280   EXPECT_TRUE(matches("template<typename T>"
281                       "T foo() { T a; return a; }"
282                       "template<typename T>"
283                       "void bar() {"
284                       "  foo<T>();"
285                       "}",
286                       unresolvedLookupExpr()));
287 }
288 
289 TEST_P(ASTMatchersTest, UsesADL) {
290   if (!GetParam().isCXX()) {
291     return;
292   }
293 
294   StatementMatcher ADLMatch = callExpr(usesADL());
295   StatementMatcher ADLMatchOper = cxxOperatorCallExpr(usesADL());
296   StringRef NS_Str = R"cpp(
297   namespace NS {
298     struct X {};
299     void f(X);
300     void operator+(X, X);
301   }
302   struct MyX {};
303   void f(...);
304   void operator+(MyX, MyX);
305 )cpp";
306 
307   auto MkStr = [&](StringRef Body) {
308     return (NS_Str + "void test_fn() { " + Body + " }").str();
309   };
310 
311   EXPECT_TRUE(matches(MkStr("NS::X x; f(x);"), ADLMatch));
312   EXPECT_TRUE(notMatches(MkStr("NS::X x; NS::f(x);"), ADLMatch));
313   EXPECT_TRUE(notMatches(MkStr("MyX x; f(x);"), ADLMatch));
314   EXPECT_TRUE(notMatches(MkStr("NS::X x; using NS::f; f(x);"), ADLMatch));
315 
316   // Operator call expressions
317   EXPECT_TRUE(matches(MkStr("NS::X x; x + x;"), ADLMatch));
318   EXPECT_TRUE(matches(MkStr("NS::X x; x + x;"), ADLMatchOper));
319   EXPECT_TRUE(notMatches(MkStr("MyX x; x + x;"), ADLMatch));
320   EXPECT_TRUE(notMatches(MkStr("MyX x; x + x;"), ADLMatchOper));
321   EXPECT_TRUE(matches(MkStr("NS::X x; operator+(x, x);"), ADLMatch));
322   EXPECT_TRUE(notMatches(MkStr("NS::X x; NS::operator+(x, x);"), ADLMatch));
323 }
324 
325 TEST_P(ASTMatchersTest, CallExpr_CXX) {
326   if (!GetParam().isCXX()) {
327     // FIXME: Add a test for `callExpr()` that does not depend on C++.
328     return;
329   }
330   // FIXME: Do we want to overload Call() to directly take
331   // Matcher<Decl>, too?
332   StatementMatcher MethodX =
333       callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
334 
335   EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
336   EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
337 
338   StatementMatcher MethodOnY =
339       cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
340 
341   EXPECT_TRUE(matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
342                       MethodOnY));
343   EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
344                       MethodOnY));
345   EXPECT_TRUE(notMatches(
346       "class Y { public: void x(); }; void z(Y *&y) { y->x(); }", MethodOnY));
347   EXPECT_TRUE(notMatches(
348       "class Y { public: void x(); }; void z(Y y[]) { y->x(); }", MethodOnY));
349   EXPECT_TRUE(notMatches(
350       "class Y { public: void x(); }; void z() { Y *y; y->x(); }", MethodOnY));
351 
352   StatementMatcher MethodOnYPointer =
353       cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
354 
355   EXPECT_TRUE(
356       matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
357               MethodOnYPointer));
358   EXPECT_TRUE(
359       matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
360               MethodOnYPointer));
361   EXPECT_TRUE(
362       matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
363               MethodOnYPointer));
364   EXPECT_TRUE(
365       notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
366                  MethodOnYPointer));
367   EXPECT_TRUE(
368       notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
369                  MethodOnYPointer));
370 }
371 
372 TEST_P(ASTMatchersTest, LambdaExpr) {
373   if (!GetParam().isCXX11OrLater()) {
374     return;
375   }
376   EXPECT_TRUE(matches("auto f = [] (int i) { return i; };", lambdaExpr()));
377 }
378 
379 TEST_P(ASTMatchersTest, CXXForRangeStmt) {
380   EXPECT_TRUE(
381       notMatches("void f() { for (int i; i<5; ++i); }", cxxForRangeStmt()));
382 }
383 
384 TEST_P(ASTMatchersTest, CXXForRangeStmt_CXX11) {
385   if (!GetParam().isCXX11OrLater()) {
386     return;
387   }
388   EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
389                       "void f() { for (auto &a : as); }",
390                       cxxForRangeStmt()));
391 }
392 
393 TEST_P(ASTMatchersTest, SubstNonTypeTemplateParmExpr) {
394   if (!GetParam().isCXX()) {
395     return;
396   }
397   EXPECT_FALSE(matches("template<int N>\n"
398                        "struct A {  static const int n = 0; };\n"
399                        "struct B : public A<42> {};",
400                        traverse(TK_AsIs, substNonTypeTemplateParmExpr())));
401   EXPECT_TRUE(matches("template<int N>\n"
402                       "struct A {  static const int n = N; };\n"
403                       "struct B : public A<42> {};",
404                       traverse(TK_AsIs, substNonTypeTemplateParmExpr())));
405 }
406 
407 TEST_P(ASTMatchersTest, NonTypeTemplateParmDecl) {
408   if (!GetParam().isCXX()) {
409     return;
410   }
411   EXPECT_TRUE(matches("template <int N> void f();",
412                       nonTypeTemplateParmDecl(hasName("N"))));
413   EXPECT_TRUE(
414       notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
415 }
416 
417 TEST_P(ASTMatchersTest, TemplateTypeParmDecl) {
418   if (!GetParam().isCXX()) {
419     return;
420   }
421   EXPECT_TRUE(matches("template <typename T> void f();",
422                       templateTypeParmDecl(hasName("T"))));
423   EXPECT_TRUE(notMatches("template <int N> void f();", templateTypeParmDecl()));
424 }
425 
426 TEST_P(ASTMatchersTest, TemplateTemplateParmDecl) {
427   if (!GetParam().isCXX())
428     return;
429   EXPECT_TRUE(matches("template <template <typename> class Z> void f();",
430                       templateTemplateParmDecl(hasName("Z"))));
431   EXPECT_TRUE(notMatches("template <typename, int> void f();",
432                          templateTemplateParmDecl()));
433 }
434 
435 TEST_P(ASTMatchersTest, UserDefinedLiteral) {
436   if (!GetParam().isCXX11OrLater()) {
437     return;
438   }
439   EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
440                       "  return i + 1;"
441                       "}"
442                       "char c = 'a'_inc;",
443                       userDefinedLiteral()));
444 }
445 
446 TEST_P(ASTMatchersTest, FlowControl) {
447   EXPECT_TRUE(matches("void f() { while(1) { break; } }", breakStmt()));
448   EXPECT_TRUE(matches("void f() { while(1) { continue; } }", continueStmt()));
449   EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
450   EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}",
451                       labelStmt(hasDeclaration(labelDecl(hasName("FOO"))))));
452   EXPECT_TRUE(matches("void f() { FOO: ; void *ptr = &&FOO; goto *ptr; }",
453                       addrLabelExpr()));
454   EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
455 }
456 
457 TEST_P(ASTMatchersTest, CXXOperatorCallExpr) {
458   if (!GetParam().isCXX()) {
459     return;
460   }
461 
462   StatementMatcher OpCall = cxxOperatorCallExpr();
463   // Unary operator
464   EXPECT_TRUE(matches("class Y { }; "
465                       "bool operator!(Y x) { return false; }; "
466                       "Y y; bool c = !y;",
467                       OpCall));
468   // No match -- special operators like "new", "delete"
469   // FIXME: operator new takes size_t, for which we need stddef.h, for which
470   // we need to figure out include paths in the test.
471   // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
472   //             "class Y { }; "
473   //             "void *operator new(size_t size) { return 0; } "
474   //             "Y *y = new Y;", OpCall));
475   EXPECT_TRUE(notMatches("class Y { }; "
476                          "void operator delete(void *p) { } "
477                          "void a() {Y *y = new Y; delete y;}",
478                          OpCall));
479   // Binary operator
480   EXPECT_TRUE(matches("class Y { }; "
481                       "bool operator&&(Y x, Y y) { return true; }; "
482                       "Y a; Y b; bool c = a && b;",
483                       OpCall));
484   // No match -- normal operator, not an overloaded one.
485   EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
486   EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
487 }
488 
489 TEST_P(ASTMatchersTest, FoldExpr) {
490   if (!GetParam().isCXX() || !GetParam().isCXX17OrLater()) {
491     return;
492   }
493 
494   EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
495                       "return (0 + ... + args); }",
496                       cxxFoldExpr()));
497   EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
498                       "return (args + ...); }",
499                       cxxFoldExpr()));
500 }
501 
502 TEST_P(ASTMatchersTest, ThisPointerType) {
503   if (!GetParam().isCXX()) {
504     return;
505   }
506 
507   StatementMatcher MethodOnY = traverse(
508       TK_AsIs, cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y")))));
509 
510   EXPECT_TRUE(matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
511                       MethodOnY));
512   EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
513                       MethodOnY));
514   EXPECT_TRUE(matches(
515       "class Y { public: void x(); }; void z(Y *&y) { y->x(); }", MethodOnY));
516   EXPECT_TRUE(matches(
517       "class Y { public: void x(); }; void z(Y y[]) { y->x(); }", MethodOnY));
518   EXPECT_TRUE(matches(
519       "class Y { public: void x(); }; void z() { Y *y; y->x(); }", MethodOnY));
520 
521   EXPECT_TRUE(matches("class Y {"
522                       "  public: virtual void x();"
523                       "};"
524                       "class X : public Y {"
525                       "  public: virtual void x();"
526                       "};"
527                       "void z() { X *x; x->Y::x(); }",
528                       MethodOnY));
529 }
530 
531 TEST_P(ASTMatchersTest, DeclRefExpr) {
532   if (!GetParam().isCXX()) {
533     // FIXME: Add a test for `declRefExpr()` that does not depend on C++.
534     return;
535   }
536   StatementMatcher Reference = declRefExpr(to(varDecl(hasInitializer(
537       cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
538 
539   EXPECT_TRUE(matches("class Y {"
540                       " public:"
541                       "  bool x() const;"
542                       "};"
543                       "void z(const Y &y) {"
544                       "  bool b = y.x();"
545                       "  if (b) {}"
546                       "}",
547                       Reference));
548 
549   EXPECT_TRUE(notMatches("class Y {"
550                          " public:"
551                          "  bool x() const;"
552                          "};"
553                          "void z(const Y &y) {"
554                          "  bool b = y.x();"
555                          "}",
556                          Reference));
557 }
558 
559 TEST_P(ASTMatchersTest, DependentScopeDeclRefExpr) {
560   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
561     // FIXME: Fix this test to work with delayed template parsing.
562     return;
563   }
564 
565   EXPECT_TRUE(matches("template <class T> class X : T { void f() { T::v; } };",
566                       dependentScopeDeclRefExpr()));
567 
568   EXPECT_TRUE(
569       matches("template <typename T> struct S { static T Foo; };"
570               "template <typename T> void declToImport() { (void)S<T>::Foo; }",
571               dependentScopeDeclRefExpr()));
572 }
573 
574 TEST_P(ASTMatchersTest, CXXMemberCallExpr) {
575   if (!GetParam().isCXX()) {
576     return;
577   }
578   StatementMatcher CallOnVariableY =
579       cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
580 
581   EXPECT_TRUE(matches("class Y { public: void x() { Y y; y.x(); } };",
582                       CallOnVariableY));
583   EXPECT_TRUE(matches("class Y { public: void x() const { Y y; y.x(); } };",
584                       CallOnVariableY));
585   EXPECT_TRUE(matches("class Y { public: void x(); };"
586                       "class X : public Y { void z() { X y; y.x(); } };",
587                       CallOnVariableY));
588   EXPECT_TRUE(matches("class Y { public: void x(); };"
589                       "class X : public Y { void z() { X *y; y->x(); } };",
590                       CallOnVariableY));
591   EXPECT_TRUE(notMatches(
592       "class Y { public: void x(); };"
593       "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
594       CallOnVariableY));
595 }
596 
597 TEST_P(ASTMatchersTest, UnaryExprOrTypeTraitExpr) {
598   EXPECT_TRUE(
599       matches("void x() { int a = sizeof(a); }", unaryExprOrTypeTraitExpr()));
600 }
601 
602 TEST_P(ASTMatchersTest, AlignOfExpr) {
603   EXPECT_TRUE(
604       notMatches("void x() { int a = sizeof(a); }", alignOfExpr(anything())));
605   // FIXME: Uncomment once alignof is enabled.
606   // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
607   //                     unaryExprOrTypeTraitExpr()));
608   // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
609   //                        sizeOfExpr()));
610 }
611 
612 TEST_P(ASTMatchersTest, MemberExpr_DoesNotMatchClasses) {
613   if (!GetParam().isCXX()) {
614     return;
615   }
616   EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
617   EXPECT_TRUE(notMatches("class Y { void x() {} };", unresolvedMemberExpr()));
618   EXPECT_TRUE(
619       notMatches("class Y { void x() {} };", cxxDependentScopeMemberExpr()));
620 }
621 
622 TEST_P(ASTMatchersTest, MemberExpr_MatchesMemberFunctionCall) {
623   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
624     // FIXME: Fix this test to work with delayed template parsing.
625     return;
626   }
627   EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
628   EXPECT_TRUE(matches("class Y { template <class T> void x() { x<T>(); } };",
629                       unresolvedMemberExpr()));
630   EXPECT_TRUE(matches("template <class T> void x() { T t; t.f(); }",
631                       cxxDependentScopeMemberExpr()));
632 }
633 
634 TEST_P(ASTMatchersTest, MemberExpr_MatchesVariable) {
635   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
636     // FIXME: Fix this test to work with delayed template parsing.
637     return;
638   }
639   EXPECT_TRUE(
640       matches("class Y { void x() { this->y; } int y; };", memberExpr()));
641   EXPECT_TRUE(matches("class Y { void x() { y; } int y; };", memberExpr()));
642   EXPECT_TRUE(
643       matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
644   EXPECT_TRUE(matches("template <class T>"
645                       "class X : T { void f() { this->T::v; } };",
646                       cxxDependentScopeMemberExpr()));
647   EXPECT_TRUE(matches("template <class T> class X : T { void f() { T::v; } };",
648                       dependentScopeDeclRefExpr()));
649   EXPECT_TRUE(matches("template <class T> void x() { T t; t.v; }",
650                       cxxDependentScopeMemberExpr()));
651 }
652 
653 TEST_P(ASTMatchersTest, MemberExpr_MatchesStaticVariable) {
654   if (!GetParam().isCXX()) {
655     return;
656   }
657   EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
658                       memberExpr()));
659   EXPECT_TRUE(
660       notMatches("class Y { void x() { y; } static int y; };", memberExpr()));
661   EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
662                          memberExpr()));
663 }
664 
665 TEST_P(ASTMatchersTest, FunctionDecl) {
666   StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
667 
668   EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
669   EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
670 
671   EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
672   EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
673   EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
674 }
675 
676 TEST_P(ASTMatchersTest, FunctionDecl_C) {
677   if (!GetParam().isC()) {
678     return;
679   }
680   EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
681   EXPECT_TRUE(matches("void f();", functionDecl(parameterCountIs(0))));
682 }
683 
684 TEST_P(ASTMatchersTest, FunctionDecl_CXX) {
685   if (!GetParam().isCXX()) {
686     return;
687   }
688 
689   StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
690 
691   if (!GetParam().hasDelayedTemplateParsing()) {
692     // FIXME: Fix this test to work with delayed template parsing.
693     // Dependent contexts, but a non-dependent call.
694     EXPECT_TRUE(
695         matches("void f(); template <int N> void g() { f(); }", CallFunctionF));
696     EXPECT_TRUE(
697         matches("void f(); template <int N> struct S { void g() { f(); } };",
698                 CallFunctionF));
699   }
700 
701   // Dependent calls don't match.
702   EXPECT_TRUE(
703       notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
704                  CallFunctionF));
705   EXPECT_TRUE(
706       notMatches("void f(int);"
707                  "template <typename T> struct S { void g(T t) { f(t); } };",
708                  CallFunctionF));
709 
710   EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
711   EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
712 }
713 
714 TEST_P(ASTMatchersTest, FunctionDecl_CXX11) {
715   if (!GetParam().isCXX11OrLater()) {
716     return;
717   }
718 
719   EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
720                          functionDecl(isVariadic())));
721 }
722 
723 TEST_P(ASTMatchersTest,
724        FunctionTemplateDecl_MatchesFunctionTemplateDeclarations) {
725   if (!GetParam().isCXX()) {
726     return;
727   }
728   EXPECT_TRUE(matches("template <typename T> void f(T t) {}",
729                       functionTemplateDecl(hasName("f"))));
730 }
731 
732 TEST_P(ASTMatchersTest, FunctionTemplate_DoesNotMatchFunctionDeclarations) {
733   EXPECT_TRUE(
734       notMatches("void f(double d);", functionTemplateDecl(hasName("f"))));
735   EXPECT_TRUE(
736       notMatches("void f(int t) {}", functionTemplateDecl(hasName("f"))));
737 }
738 
739 TEST_P(ASTMatchersTest,
740        FunctionTemplateDecl_DoesNotMatchFunctionTemplateSpecializations) {
741   if (!GetParam().isCXX()) {
742     return;
743   }
744   EXPECT_TRUE(notMatches(
745       "void g(); template <typename T> void f(T t) {}"
746       "template <> void f(int t) { g(); }",
747       functionTemplateDecl(hasName("f"), hasDescendant(declRefExpr(to(
748                                              functionDecl(hasName("g"))))))));
749 }
750 
751 TEST_P(ASTMatchersTest, ClassTemplateSpecializationDecl) {
752   if (!GetParam().isCXX()) {
753     return;
754   }
755   EXPECT_TRUE(matches("template<typename T> struct A {};"
756                       "template<> struct A<int> {};",
757                       classTemplateSpecializationDecl()));
758   EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
759                       classTemplateSpecializationDecl()));
760   EXPECT_TRUE(notMatches("template<typename T> struct A {};",
761                          classTemplateSpecializationDecl()));
762 }
763 
764 TEST_P(ASTMatchersTest, DeclaratorDecl) {
765   EXPECT_TRUE(matches("int x;", declaratorDecl()));
766   EXPECT_TRUE(notMatches("struct A {};", declaratorDecl()));
767 }
768 
769 TEST_P(ASTMatchersTest, DeclaratorDecl_CXX) {
770   if (!GetParam().isCXX()) {
771     return;
772   }
773   EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
774 }
775 
776 TEST_P(ASTMatchersTest, ParmVarDecl) {
777   EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
778   EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
779 }
780 
781 TEST_P(ASTMatchersTest, StaticAssertDecl) {
782   if (!GetParam().isCXX11OrLater())
783     return;
784 
785   EXPECT_TRUE(matches("static_assert(true, \"\");", staticAssertDecl()));
786   EXPECT_TRUE(
787       notMatches("constexpr bool staticassert(bool B, const char *M) "
788                  "{ return true; };\n void f() { staticassert(true, \"\"); }",
789                  staticAssertDecl()));
790 }
791 
792 TEST_P(ASTMatchersTest, Matcher_ConstructorCall) {
793   if (!GetParam().isCXX()) {
794     return;
795   }
796 
797   StatementMatcher Constructor = traverse(TK_AsIs, cxxConstructExpr());
798 
799   EXPECT_TRUE(
800       matches("class X { public: X(); }; void x() { X x; }", Constructor));
801   EXPECT_TRUE(matches("class X { public: X(); }; void x() { X x = X(); }",
802                       Constructor));
803   EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = 0; }",
804                       Constructor));
805   EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
806 }
807 
808 TEST_P(ASTMatchersTest, Match_ConstructorInitializers) {
809   if (!GetParam().isCXX()) {
810     return;
811   }
812   EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };",
813                       cxxCtorInitializer(forField(hasName("i")))));
814 }
815 
816 TEST_P(ASTMatchersTest, Matcher_ThisExpr) {
817   if (!GetParam().isCXX()) {
818     return;
819   }
820   EXPECT_TRUE(
821       matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
822   EXPECT_TRUE(
823       notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
824 }
825 
826 TEST_P(ASTMatchersTest, Matcher_BindTemporaryExpression) {
827   if (!GetParam().isCXX()) {
828     return;
829   }
830 
831   StatementMatcher TempExpression = traverse(TK_AsIs, cxxBindTemporaryExpr());
832 
833   StringRef ClassString = "class string { public: string(); ~string(); }; ";
834 
835   EXPECT_TRUE(matches(
836       ClassString + "string GetStringByValue();"
837                     "void FunctionTakesString(string s);"
838                     "void run() { FunctionTakesString(GetStringByValue()); }",
839       TempExpression));
840 
841   EXPECT_TRUE(notMatches(ClassString +
842                              "string* GetStringPointer(); "
843                              "void FunctionTakesStringPtr(string* s);"
844                              "void run() {"
845                              "  string* s = GetStringPointer();"
846                              "  FunctionTakesStringPtr(GetStringPointer());"
847                              "  FunctionTakesStringPtr(s);"
848                              "}",
849                          TempExpression));
850 
851   EXPECT_TRUE(notMatches("class no_dtor {};"
852                          "no_dtor GetObjByValue();"
853                          "void ConsumeObj(no_dtor param);"
854                          "void run() { ConsumeObj(GetObjByValue()); }",
855                          TempExpression));
856 }
857 
858 TEST_P(ASTMatchersTest, MaterializeTemporaryExpr_MatchesTemporaryCXX11CXX14) {
859   if (GetParam().Language != Lang_CXX11 && GetParam().Language != Lang_CXX14) {
860     return;
861   }
862 
863   StatementMatcher TempExpression =
864       traverse(TK_AsIs, materializeTemporaryExpr());
865 
866   EXPECT_TRUE(matches("class string { public: string(); }; "
867                       "string GetStringByValue();"
868                       "void FunctionTakesString(string s);"
869                       "void run() { FunctionTakesString(GetStringByValue()); }",
870                       TempExpression));
871 }
872 
873 TEST_P(ASTMatchersTest, MaterializeTemporaryExpr_MatchesTemporary) {
874   if (!GetParam().isCXX()) {
875     return;
876   }
877 
878   StringRef ClassString = "class string { public: string(); int length(); }; ";
879   StatementMatcher TempExpression =
880       traverse(TK_AsIs, materializeTemporaryExpr());
881 
882   EXPECT_TRUE(notMatches(ClassString +
883                              "string* GetStringPointer(); "
884                              "void FunctionTakesStringPtr(string* s);"
885                              "void run() {"
886                              "  string* s = GetStringPointer();"
887                              "  FunctionTakesStringPtr(GetStringPointer());"
888                              "  FunctionTakesStringPtr(s);"
889                              "}",
890                          TempExpression));
891 
892   EXPECT_TRUE(matches(ClassString +
893                           "string GetStringByValue();"
894                           "void run() { int k = GetStringByValue().length(); }",
895                       TempExpression));
896 
897   EXPECT_TRUE(notMatches(ClassString + "string GetStringByValue();"
898                                        "void run() { GetStringByValue(); }",
899                          TempExpression));
900 }
901 
902 TEST_P(ASTMatchersTest, Matcher_NewExpression) {
903   if (!GetParam().isCXX()) {
904     return;
905   }
906 
907   StatementMatcher New = cxxNewExpr();
908 
909   EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
910   EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X(); }", New));
911   EXPECT_TRUE(
912       matches("class X { public: X(int); }; void x() { new X(0); }", New));
913   EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
914 }
915 
916 TEST_P(ASTMatchersTest, Matcher_DeleteExpression) {
917   if (!GetParam().isCXX()) {
918     return;
919   }
920   EXPECT_TRUE(
921       matches("struct A {}; void f(A* a) { delete a; }", cxxDeleteExpr()));
922 }
923 
924 TEST_P(ASTMatchersTest, Matcher_NoexceptExpression) {
925   if (!GetParam().isCXX11OrLater()) {
926     return;
927   }
928   StatementMatcher NoExcept = cxxNoexceptExpr();
929   EXPECT_TRUE(matches("void foo(); bool bar = noexcept(foo());", NoExcept));
930   EXPECT_TRUE(
931       matches("void foo() noexcept; bool bar = noexcept(foo());", NoExcept));
932   EXPECT_TRUE(notMatches("void foo() noexcept;", NoExcept));
933   EXPECT_TRUE(notMatches("void foo() noexcept(0+1);", NoExcept));
934   EXPECT_TRUE(matches("void foo() noexcept(noexcept(1+1));", NoExcept));
935 }
936 
937 TEST_P(ASTMatchersTest, Matcher_DefaultArgument) {
938   if (!GetParam().isCXX()) {
939     return;
940   }
941   StatementMatcher Arg = cxxDefaultArgExpr();
942   EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
943   EXPECT_TRUE(
944       matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
945   EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
946 }
947 
948 TEST_P(ASTMatchersTest, StringLiteral) {
949   StatementMatcher Literal = stringLiteral();
950   EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
951   // with escaped characters
952   EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
953   // no matching -- though the data type is the same, there is no string literal
954   EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
955 }
956 
957 TEST_P(ASTMatchersTest, StringLiteral_CXX) {
958   if (!GetParam().isCXX()) {
959     return;
960   }
961   EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", stringLiteral()));
962 }
963 
964 TEST_P(ASTMatchersTest, CharacterLiteral) {
965   EXPECT_TRUE(matches("const char c = 'c';", characterLiteral()));
966   EXPECT_TRUE(notMatches("const char c = 0x1;", characterLiteral()));
967 }
968 
969 TEST_P(ASTMatchersTest, CharacterLiteral_CXX) {
970   if (!GetParam().isCXX()) {
971     return;
972   }
973   // wide character
974   EXPECT_TRUE(matches("const char c = L'c';", characterLiteral()));
975   // wide character, Hex encoded, NOT MATCHED!
976   EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", characterLiteral()));
977 }
978 
979 TEST_P(ASTMatchersTest, IntegerLiteral) {
980   StatementMatcher HasIntLiteral = integerLiteral();
981   EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
982   EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
983   EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
984   EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
985 
986   // Non-matching cases (character literals, float and double)
987   EXPECT_TRUE(notMatches("int i = L'a';",
988                          HasIntLiteral)); // this is actually a character
989   // literal cast to int
990   EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
991   EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
992   EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
993 
994   // Negative integers.
995   EXPECT_TRUE(
996       matches("int i = -10;",
997               unaryOperator(hasOperatorName("-"),
998                             hasUnaryOperand(integerLiteral(equals(10))))));
999 }
1000 
1001 TEST_P(ASTMatchersTest, FloatLiteral) {
1002   StatementMatcher HasFloatLiteral = floatLiteral();
1003   EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
1004   EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
1005   EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
1006   EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
1007   EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
1008   EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
1009   EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
1010   EXPECT_TRUE(
1011       matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
1012 
1013   EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
1014   EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
1015   EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
1016   EXPECT_TRUE(
1017       notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
1018 }
1019 
1020 TEST_P(ASTMatchersTest, CXXNullPtrLiteralExpr) {
1021   if (!GetParam().isCXX11OrLater()) {
1022     return;
1023   }
1024   EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
1025 }
1026 
1027 TEST_P(ASTMatchersTest, ChooseExpr) {
1028   EXPECT_TRUE(matches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
1029                       chooseExpr()));
1030 }
1031 
1032 TEST_P(ASTMatchersTest, ConvertVectorExpr) {
1033   EXPECT_TRUE(matches(
1034       "typedef double vector4double __attribute__((__vector_size__(32)));"
1035       "typedef float  vector4float  __attribute__((__vector_size__(16)));"
1036       "vector4float vf;"
1037       "void f() { (void)__builtin_convertvector(vf, vector4double); }",
1038       convertVectorExpr()));
1039   EXPECT_TRUE(notMatches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
1040                          convertVectorExpr()));
1041 }
1042 
1043 TEST_P(ASTMatchersTest, GNUNullExpr) {
1044   if (!GetParam().isCXX()) {
1045     return;
1046   }
1047   EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
1048 }
1049 
1050 TEST_P(ASTMatchersTest, GenericSelectionExpr) {
1051   EXPECT_TRUE(matches("void f() { (void)_Generic(1, int: 1, float: 2.0); }",
1052                       genericSelectionExpr()));
1053 }
1054 
1055 TEST_P(ASTMatchersTest, AtomicExpr) {
1056   EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
1057                       atomicExpr()));
1058 }
1059 
1060 TEST_P(ASTMatchersTest, Initializers_C99) {
1061   if (!GetParam().isC99OrLater()) {
1062     return;
1063   }
1064   EXPECT_TRUE(matches(
1065       "void foo() { struct point { double x; double y; };"
1066       "  struct point ptarray[10] = "
1067       "      { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1068       initListExpr(hasSyntacticForm(initListExpr(
1069           has(designatedInitExpr(designatorCountIs(2),
1070                                  hasDescendant(floatLiteral(equals(1.0))),
1071                                  hasDescendant(integerLiteral(equals(2))))),
1072           has(designatedInitExpr(designatorCountIs(2),
1073                                  hasDescendant(floatLiteral(equals(2.0))),
1074                                  hasDescendant(integerLiteral(equals(2))))),
1075           has(designatedInitExpr(
1076               designatorCountIs(2), hasDescendant(floatLiteral(equals(1.0))),
1077               hasDescendant(integerLiteral(equals(0))))))))));
1078 }
1079 
1080 TEST_P(ASTMatchersTest, Initializers_CXX) {
1081   if (GetParam().Language != Lang_CXX03) {
1082     // FIXME: Make this test pass with other C++ standard versions.
1083     return;
1084   }
1085   EXPECT_TRUE(matches(
1086       "void foo() { struct point { double x; double y; };"
1087       "  struct point ptarray[10] = "
1088       "      { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1089       initListExpr(
1090           has(cxxConstructExpr(requiresZeroInitialization())),
1091           has(initListExpr(
1092               hasType(asString("struct point")), has(floatLiteral(equals(1.0))),
1093               has(implicitValueInitExpr(hasType(asString("double")))))),
1094           has(initListExpr(hasType(asString("struct point")),
1095                            has(floatLiteral(equals(2.0))),
1096                            has(floatLiteral(equals(1.0))))))));
1097 }
1098 
1099 TEST_P(ASTMatchersTest, ParenListExpr) {
1100   if (!GetParam().isCXX()) {
1101     return;
1102   }
1103   EXPECT_TRUE(
1104       matches("template<typename T> class foo { void bar() { foo X(*this); } };"
1105               "template class foo<int>;",
1106               varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
1107 }
1108 
1109 TEST_P(ASTMatchersTest, StmtExpr) {
1110   EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
1111                       varDecl(hasInitializer(stmtExpr()))));
1112 }
1113 
1114 TEST_P(ASTMatchersTest, PredefinedExpr) {
1115   // __func__ expands as StringLiteral("foo")
1116   EXPECT_TRUE(matches("void foo() { __func__; }",
1117                       predefinedExpr(hasType(asString("const char[4]")),
1118                                      has(stringLiteral()))));
1119 }
1120 
1121 TEST_P(ASTMatchersTest, AsmStatement) {
1122   EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1123 }
1124 
1125 TEST_P(ASTMatchersTest, HasCondition) {
1126   if (!GetParam().isCXX()) {
1127     // FIXME: Add a test for `hasCondition()` that does not depend on C++.
1128     return;
1129   }
1130 
1131   StatementMatcher Condition =
1132       ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
1133 
1134   EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
1135   EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
1136   EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
1137   EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
1138   EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
1139 }
1140 
1141 TEST_P(ASTMatchersTest, ConditionalOperator) {
1142   if (!GetParam().isCXX()) {
1143     // FIXME: Add a test for `conditionalOperator()` that does not depend on
1144     // C++.
1145     return;
1146   }
1147 
1148   StatementMatcher Conditional =
1149       conditionalOperator(hasCondition(cxxBoolLiteral(equals(true))),
1150                           hasTrueExpression(cxxBoolLiteral(equals(false))));
1151 
1152   EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
1153   EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
1154   EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
1155 
1156   StatementMatcher ConditionalFalse =
1157       conditionalOperator(hasFalseExpression(cxxBoolLiteral(equals(false))));
1158 
1159   EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1160   EXPECT_TRUE(
1161       notMatches("void x() { true ? false : true; }", ConditionalFalse));
1162 
1163   EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1164   EXPECT_TRUE(
1165       notMatches("void x() { true ? false : true; }", ConditionalFalse));
1166 }
1167 
1168 TEST_P(ASTMatchersTest, BinaryConditionalOperator) {
1169   if (!GetParam().isCXX()) {
1170     // FIXME: This test should work in non-C++ language modes.
1171     return;
1172   }
1173 
1174   StatementMatcher AlwaysOne = traverse(
1175       TK_AsIs, binaryConditionalOperator(
1176                    hasCondition(implicitCastExpr(has(opaqueValueExpr(
1177                        hasSourceExpression((integerLiteral(equals(1)))))))),
1178                    hasFalseExpression(integerLiteral(equals(0)))));
1179 
1180   EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne));
1181 
1182   StatementMatcher FourNotFive = binaryConditionalOperator(
1183       hasTrueExpression(
1184           opaqueValueExpr(hasSourceExpression((integerLiteral(equals(4)))))),
1185       hasFalseExpression(integerLiteral(equals(5))));
1186 
1187   EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive));
1188 }
1189 
1190 TEST_P(ASTMatchersTest, ArraySubscriptExpr) {
1191   EXPECT_TRUE(
1192       matches("int i[2]; void f() { i[1] = 1; }", arraySubscriptExpr()));
1193   EXPECT_TRUE(notMatches("int i; void f() { i = 1; }", arraySubscriptExpr()));
1194 }
1195 
1196 TEST_P(ASTMatchersTest, ForStmt) {
1197   EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
1198   EXPECT_TRUE(matches("void f() { if(1) for(;;); }", forStmt()));
1199 }
1200 
1201 TEST_P(ASTMatchersTest, ForStmt_CXX11) {
1202   if (!GetParam().isCXX11OrLater()) {
1203     return;
1204   }
1205   EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
1206                          "void f() { for (auto &a : as); }",
1207                          forStmt()));
1208 }
1209 
1210 TEST_P(ASTMatchersTest, ForStmt_NoFalsePositives) {
1211   EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
1212   EXPECT_TRUE(notMatches("void f() { if(1); }", forStmt()));
1213 }
1214 
1215 TEST_P(ASTMatchersTest, CompoundStatement) {
1216   EXPECT_TRUE(notMatches("void f();", compoundStmt()));
1217   EXPECT_TRUE(matches("void f() {}", compoundStmt()));
1218   EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
1219 }
1220 
1221 TEST_P(ASTMatchersTest, CompoundStatement_DoesNotMatchEmptyStruct) {
1222   if (!GetParam().isCXX()) {
1223     // FIXME: Add a similar test that does not depend on C++.
1224     return;
1225   }
1226   // It's not a compound statement just because there's "{}" in the source
1227   // text. This is an AST search, not grep.
1228   EXPECT_TRUE(notMatches("namespace n { struct S {}; }", compoundStmt()));
1229   EXPECT_TRUE(
1230       matches("namespace n { struct S { void f() {{}} }; }", compoundStmt()));
1231 }
1232 
1233 TEST_P(ASTMatchersTest, CastExpr_MatchesExplicitCasts) {
1234   EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
1235 }
1236 
1237 TEST_P(ASTMatchersTest, CastExpr_MatchesExplicitCasts_CXX) {
1238   if (!GetParam().isCXX()) {
1239     return;
1240   }
1241   EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);", castExpr()));
1242   EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
1243   EXPECT_TRUE(matches("char c = char(0);", castExpr()));
1244 }
1245 
1246 TEST_P(ASTMatchersTest, CastExpression_MatchesImplicitCasts) {
1247   // This test creates an implicit cast from int to char.
1248   EXPECT_TRUE(matches("char c = 0;", traverse(TK_AsIs, castExpr())));
1249   // This test creates an implicit cast from lvalue to rvalue.
1250   EXPECT_TRUE(matches("void f() { char c = 0, d = c; }",
1251                       traverse(TK_AsIs, castExpr())));
1252 }
1253 
1254 TEST_P(ASTMatchersTest, CastExpr_DoesNotMatchNonCasts) {
1255   if (GetParam().isC()) {
1256     // This does have a cast in C
1257     EXPECT_TRUE(matches("char c = '0';", implicitCastExpr()));
1258   } else {
1259     EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
1260   }
1261   EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
1262   EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
1263 }
1264 
1265 TEST_P(ASTMatchersTest, CastExpr_DoesNotMatchNonCasts_CXX) {
1266   if (!GetParam().isCXX()) {
1267     return;
1268   }
1269   EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
1270 }
1271 
1272 TEST_P(ASTMatchersTest, CXXReinterpretCastExpr) {
1273   if (!GetParam().isCXX()) {
1274     return;
1275   }
1276   EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
1277                       cxxReinterpretCastExpr()));
1278 }
1279 
1280 TEST_P(ASTMatchersTest, CXXReinterpretCastExpr_DoesNotMatchOtherCasts) {
1281   if (!GetParam().isCXX()) {
1282     return;
1283   }
1284   EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
1285   EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
1286                          cxxReinterpretCastExpr()));
1287   EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
1288                          cxxReinterpretCastExpr()));
1289   EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1290                          "B b;"
1291                          "D* p = dynamic_cast<D*>(&b);",
1292                          cxxReinterpretCastExpr()));
1293 }
1294 
1295 TEST_P(ASTMatchersTest, CXXFunctionalCastExpr_MatchesSimpleCase) {
1296   if (!GetParam().isCXX()) {
1297     return;
1298   }
1299   StringRef foo_class = "class Foo { public: Foo(const char*); };";
1300   EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
1301                       cxxFunctionalCastExpr()));
1302 }
1303 
1304 TEST_P(ASTMatchersTest, CXXFunctionalCastExpr_DoesNotMatchOtherCasts) {
1305   if (!GetParam().isCXX()) {
1306     return;
1307   }
1308   StringRef FooClass = "class Foo { public: Foo(const char*); };";
1309   EXPECT_TRUE(
1310       notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
1311                  cxxFunctionalCastExpr()));
1312   EXPECT_TRUE(notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
1313                          cxxFunctionalCastExpr()));
1314 }
1315 
1316 TEST_P(ASTMatchersTest, CXXDynamicCastExpr) {
1317   if (!GetParam().isCXX()) {
1318     return;
1319   }
1320   EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
1321                       "B b;"
1322                       "D* p = dynamic_cast<D*>(&b);",
1323                       cxxDynamicCastExpr()));
1324 }
1325 
1326 TEST_P(ASTMatchersTest, CXXStaticCastExpr_MatchesSimpleCase) {
1327   if (!GetParam().isCXX()) {
1328     return;
1329   }
1330   EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));", cxxStaticCastExpr()));
1331 }
1332 
1333 TEST_P(ASTMatchersTest, CXXStaticCastExpr_DoesNotMatchOtherCasts) {
1334   if (!GetParam().isCXX()) {
1335     return;
1336   }
1337   EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
1338   EXPECT_TRUE(
1339       notMatches("char q, *p = const_cast<char*>(&q);", cxxStaticCastExpr()));
1340   EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
1341                          cxxStaticCastExpr()));
1342   EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1343                          "B b;"
1344                          "D* p = dynamic_cast<D*>(&b);",
1345                          cxxStaticCastExpr()));
1346 }
1347 
1348 TEST_P(ASTMatchersTest, CStyleCastExpr_MatchesSimpleCase) {
1349   EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
1350 }
1351 
1352 TEST_P(ASTMatchersTest, CStyleCastExpr_DoesNotMatchOtherCasts) {
1353   if (!GetParam().isCXX()) {
1354     return;
1355   }
1356   EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
1357                          "char q, *r = const_cast<char*>(&q);"
1358                          "void* s = reinterpret_cast<char*>(&s);"
1359                          "struct B { virtual ~B() {} }; struct D : B {};"
1360                          "B b;"
1361                          "D* t = dynamic_cast<D*>(&b);",
1362                          cStyleCastExpr()));
1363 }
1364 
1365 TEST_P(ASTMatchersTest, ImplicitCastExpr_MatchesSimpleCase) {
1366   // This test creates an implicit const cast.
1367   EXPECT_TRUE(
1368       matches("void f() { int x = 0; const int y = x; }",
1369               traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1370   // This test creates an implicit cast from int to char.
1371   EXPECT_TRUE(
1372       matches("char c = 0;",
1373               traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1374   // This test creates an implicit array-to-pointer cast.
1375   EXPECT_TRUE(
1376       matches("int arr[6]; int *p = arr;",
1377               traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1378 }
1379 
1380 TEST_P(ASTMatchersTest, ImplicitCastExpr_DoesNotMatchIncorrectly) {
1381   // This test verifies that implicitCastExpr() matches exactly when implicit
1382   // casts are present, and that it ignores explicit and paren casts.
1383 
1384   // These two test cases have no casts.
1385   EXPECT_TRUE(
1386       notMatches("int x = 0;", varDecl(hasInitializer(implicitCastExpr()))));
1387   EXPECT_TRUE(
1388       notMatches("int x = (0);", varDecl(hasInitializer(implicitCastExpr()))));
1389   EXPECT_TRUE(notMatches("void f() { int x = 0; double d = (double) x; }",
1390                          varDecl(hasInitializer(implicitCastExpr()))));
1391 }
1392 
1393 TEST_P(ASTMatchersTest, ImplicitCastExpr_DoesNotMatchIncorrectly_CXX) {
1394   if (!GetParam().isCXX()) {
1395     return;
1396   }
1397   EXPECT_TRUE(notMatches("int x = 0, &y = x;",
1398                          varDecl(hasInitializer(implicitCastExpr()))));
1399   EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
1400                          varDecl(hasInitializer(implicitCastExpr()))));
1401 }
1402 
1403 TEST_P(ASTMatchersTest, Stmt_DoesNotMatchDeclarations) {
1404   EXPECT_TRUE(notMatches("struct X {};", stmt()));
1405 }
1406 
1407 TEST_P(ASTMatchersTest, Stmt_MatchesCompoundStatments) {
1408   EXPECT_TRUE(matches("void x() {}", stmt()));
1409 }
1410 
1411 TEST_P(ASTMatchersTest, DeclStmt_DoesNotMatchCompoundStatements) {
1412   EXPECT_TRUE(notMatches("void x() {}", declStmt()));
1413 }
1414 
1415 TEST_P(ASTMatchersTest, DeclStmt_MatchesVariableDeclarationStatements) {
1416   EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
1417 }
1418 
1419 TEST_P(ASTMatchersTest, ExprWithCleanups_MatchesExprWithCleanups) {
1420   if (!GetParam().isCXX()) {
1421     return;
1422   }
1423   EXPECT_TRUE(
1424       matches("struct Foo { ~Foo(); };"
1425               "const Foo f = Foo();",
1426               traverse(TK_AsIs, varDecl(hasInitializer(exprWithCleanups())))));
1427   EXPECT_FALSE(
1428       matches("struct Foo { }; Foo a;"
1429               "const Foo f = a;",
1430               traverse(TK_AsIs, varDecl(hasInitializer(exprWithCleanups())))));
1431 }
1432 
1433 TEST_P(ASTMatchersTest, InitListExpr) {
1434   EXPECT_TRUE(matches("int a[] = { 1, 2 };",
1435                       initListExpr(hasType(asString("int[2]")))));
1436   EXPECT_TRUE(matches("struct B { int x, y; }; struct B b = { 5, 6 };",
1437                       initListExpr(hasType(recordDecl(hasName("B"))))));
1438   EXPECT_TRUE(
1439       matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
1440 }
1441 
1442 TEST_P(ASTMatchersTest, InitListExpr_CXX) {
1443   if (!GetParam().isCXX()) {
1444     return;
1445   }
1446   EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
1447                       "void f();"
1448                       "S s[1] = { &f };",
1449                       declRefExpr(to(functionDecl(hasName("f"))))));
1450 }
1451 
1452 TEST_P(ASTMatchersTest,
1453        CXXStdInitializerListExpression_MatchesCXXStdInitializerListExpression) {
1454   if (!GetParam().isCXX11OrLater()) {
1455     return;
1456   }
1457   StringRef code = "namespace std {"
1458                    "template <typename E> class initializer_list {"
1459                    "  public: const E *a, *b;"
1460                    "};"
1461                    "}"
1462                    "struct A {"
1463                    "  A(std::initializer_list<int>) {}"
1464                    "};";
1465   EXPECT_TRUE(matches(
1466       code + "A a{0};",
1467       traverse(TK_AsIs, cxxConstructExpr(has(cxxStdInitializerListExpr()),
1468                                          hasDeclaration(cxxConstructorDecl(
1469                                              ofClass(hasName("A"))))))));
1470   EXPECT_TRUE(matches(
1471       code + "A a = {0};",
1472       traverse(TK_AsIs, cxxConstructExpr(has(cxxStdInitializerListExpr()),
1473                                          hasDeclaration(cxxConstructorDecl(
1474                                              ofClass(hasName("A"))))))));
1475 
1476   EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr()));
1477   EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };",
1478                          cxxStdInitializerListExpr()));
1479 }
1480 
1481 TEST_P(ASTMatchersTest, UsingDecl_MatchesUsingDeclarations) {
1482   if (!GetParam().isCXX()) {
1483     return;
1484   }
1485   EXPECT_TRUE(matches("namespace X { int x; } using X::x;", usingDecl()));
1486 }
1487 
1488 TEST_P(ASTMatchersTest, UsingDecl_MatchesShadowUsingDelcarations) {
1489   if (!GetParam().isCXX()) {
1490     return;
1491   }
1492   EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
1493                       usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
1494 }
1495 
1496 TEST_P(ASTMatchersTest, UsingEnumDecl_MatchesUsingEnumDeclarations) {
1497   if (!GetParam().isCXX20OrLater()) {
1498     return;
1499   }
1500   EXPECT_TRUE(
1501       matches("namespace X { enum x {}; } using enum X::x;", usingEnumDecl()));
1502 }
1503 
1504 TEST_P(ASTMatchersTest, UsingEnumDecl_MatchesShadowUsingDeclarations) {
1505   if (!GetParam().isCXX20OrLater()) {
1506     return;
1507   }
1508   EXPECT_TRUE(matches("namespace f { enum a {b}; } using enum f::a;",
1509                       usingEnumDecl(hasAnyUsingShadowDecl(hasName("b")))));
1510 }
1511 
1512 TEST_P(ASTMatchersTest, UsingDirectiveDecl_MatchesUsingNamespace) {
1513   if (!GetParam().isCXX()) {
1514     return;
1515   }
1516   EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
1517                       usingDirectiveDecl()));
1518   EXPECT_FALSE(
1519       matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
1520 }
1521 
1522 TEST_P(ASTMatchersTest, WhileStmt) {
1523   EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1524   EXPECT_TRUE(matches("void x() { while(1); }", whileStmt()));
1525   EXPECT_TRUE(notMatches("void x() { do {} while(1); }", whileStmt()));
1526 }
1527 
1528 TEST_P(ASTMatchersTest, DoStmt_MatchesDoLoops) {
1529   EXPECT_TRUE(matches("void x() { do {} while(1); }", doStmt()));
1530   EXPECT_TRUE(matches("void x() { do ; while(0); }", doStmt()));
1531 }
1532 
1533 TEST_P(ASTMatchersTest, DoStmt_DoesNotMatchWhileLoops) {
1534   EXPECT_TRUE(notMatches("void x() { while(1) {} }", doStmt()));
1535 }
1536 
1537 TEST_P(ASTMatchersTest, SwitchCase_MatchesCase) {
1538   EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1539   EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1540   EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1541   EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1542 }
1543 
1544 TEST_P(ASTMatchersTest, SwitchCase_MatchesSwitch) {
1545   EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
1546   EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
1547   EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
1548   EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
1549 }
1550 
1551 TEST_P(ASTMatchersTest, CxxExceptionHandling_SimpleCases) {
1552   if (!GetParam().isCXX()) {
1553     return;
1554   }
1555   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
1556   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
1557   EXPECT_TRUE(
1558       notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
1559   EXPECT_TRUE(
1560       matches("void foo() try { throw; } catch(int X) { }", cxxThrowExpr()));
1561   EXPECT_TRUE(
1562       matches("void foo() try { throw 5;} catch(int X) { }", cxxThrowExpr()));
1563   EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
1564                       cxxCatchStmt(isCatchAll())));
1565   EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
1566                          cxxCatchStmt(isCatchAll())));
1567   EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
1568                       varDecl(isExceptionVariable())));
1569   EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
1570                          varDecl(isExceptionVariable())));
1571 }
1572 
1573 TEST_P(ASTMatchersTest, ParenExpr_SimpleCases) {
1574   EXPECT_TRUE(matches("int i = (3);", traverse(TK_AsIs, parenExpr())));
1575   EXPECT_TRUE(matches("int i = (3 + 7);", traverse(TK_AsIs, parenExpr())));
1576   EXPECT_TRUE(notMatches("int i = 3;", traverse(TK_AsIs, parenExpr())));
1577   EXPECT_TRUE(notMatches("int f() { return 1; }; void g() { int a = f(); }",
1578                          traverse(TK_AsIs, parenExpr())));
1579 }
1580 
1581 TEST_P(ASTMatchersTest, IgnoringParens) {
1582   EXPECT_FALSE(matches("const char* str = (\"my-string\");",
1583                        traverse(TK_AsIs, implicitCastExpr(hasSourceExpression(
1584                                              stringLiteral())))));
1585   EXPECT_TRUE(
1586       matches("const char* str = (\"my-string\");",
1587               traverse(TK_AsIs, implicitCastExpr(hasSourceExpression(
1588                                     ignoringParens(stringLiteral()))))));
1589 }
1590 
1591 TEST_P(ASTMatchersTest, QualType) {
1592   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
1593 }
1594 
1595 TEST_P(ASTMatchersTest, ConstantArrayType) {
1596   EXPECT_TRUE(matches("int a[2];", constantArrayType()));
1597   EXPECT_TRUE(notMatches("void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
1598                          constantArrayType(hasElementType(builtinType()))));
1599 
1600   EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
1601   EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
1602   EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
1603 }
1604 
1605 TEST_P(ASTMatchersTest, DependentSizedArrayType) {
1606   if (!GetParam().isCXX()) {
1607     return;
1608   }
1609   EXPECT_TRUE(
1610       matches("template <typename T, int Size> class array { T data[Size]; };",
1611               dependentSizedArrayType()));
1612   EXPECT_TRUE(
1613       notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1614                  dependentSizedArrayType()));
1615 }
1616 
1617 TEST_P(ASTMatchersTest, DependentSizedExtVectorType) {
1618   if (!GetParam().isCXX()) {
1619     return;
1620   }
1621   EXPECT_TRUE(matches("template<typename T, int Size>"
1622                       "class vector {"
1623                       "  typedef T __attribute__((ext_vector_type(Size))) type;"
1624                       "};",
1625                       dependentSizedExtVectorType()));
1626   EXPECT_TRUE(
1627       notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1628                  dependentSizedExtVectorType()));
1629 }
1630 
1631 TEST_P(ASTMatchersTest, IncompleteArrayType) {
1632   EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
1633   EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
1634 
1635   EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
1636                          incompleteArrayType()));
1637 }
1638 
1639 TEST_P(ASTMatchersTest, VariableArrayType) {
1640   EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
1641   EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
1642 
1643   EXPECT_TRUE(matches("void f(int b) { int a[b]; }",
1644                       variableArrayType(hasSizeExpr(ignoringImpCasts(
1645                           declRefExpr(to(varDecl(hasName("b")))))))));
1646 }
1647 
1648 TEST_P(ASTMatchersTest, AtomicType) {
1649   if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1650       llvm::Triple::Win32) {
1651     // FIXME: Make this work for MSVC.
1652     EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
1653 
1654     EXPECT_TRUE(
1655         matches("_Atomic(int) i;", atomicType(hasValueType(isInteger()))));
1656     EXPECT_TRUE(
1657         notMatches("_Atomic(float) f;", atomicType(hasValueType(isInteger()))));
1658   }
1659 }
1660 
1661 TEST_P(ASTMatchersTest, AutoType) {
1662   if (!GetParam().isCXX11OrLater()) {
1663     return;
1664   }
1665   EXPECT_TRUE(matches("auto i = 2;", autoType()));
1666   EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
1667                       autoType()));
1668 
1669   EXPECT_TRUE(matches("auto i = 2;", varDecl(hasType(isInteger()))));
1670   EXPECT_TRUE(matches("struct X{}; auto x = X{};",
1671                       varDecl(hasType(recordDecl(hasName("X"))))));
1672 
1673   // FIXME: Matching against the type-as-written can't work here, because the
1674   //        type as written was not deduced.
1675   // EXPECT_TRUE(matches("auto a = 1;",
1676   //                    autoType(hasDeducedType(isInteger()))));
1677   // EXPECT_TRUE(notMatches("auto b = 2.0;",
1678   //                       autoType(hasDeducedType(isInteger()))));
1679 }
1680 
1681 TEST_P(ASTMatchersTest, DecltypeType) {
1682   if (!GetParam().isCXX11OrLater()) {
1683     return;
1684   }
1685   EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;", decltypeType()));
1686   EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;",
1687                       decltypeType(hasUnderlyingType(isInteger()))));
1688 }
1689 
1690 TEST_P(ASTMatchersTest, FunctionType) {
1691   EXPECT_TRUE(matches("int (*f)(int);", functionType()));
1692   EXPECT_TRUE(matches("void f(int i) {}", functionType()));
1693 }
1694 
1695 TEST_P(ASTMatchersTest, IgnoringParens_Type) {
1696   EXPECT_TRUE(
1697       notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
1698   EXPECT_TRUE(matches("void (*fp)(void);",
1699                       pointerType(pointee(ignoringParens(functionType())))));
1700 }
1701 
1702 TEST_P(ASTMatchersTest, FunctionProtoType) {
1703   EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
1704   EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
1705   EXPECT_TRUE(matches("void f(void);", functionProtoType(parameterCountIs(0))));
1706 }
1707 
1708 TEST_P(ASTMatchersTest, FunctionProtoType_C) {
1709   if (!GetParam().isCOrEarlier(17)) {
1710     return;
1711   }
1712   EXPECT_TRUE(notMatches("void f();", functionProtoType()));
1713 }
1714 
1715 TEST_P(ASTMatchersTest, FunctionProtoType_CXX) {
1716   if (!GetParam().isCXX()) {
1717     return;
1718   }
1719   EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
1720 }
1721 
1722 TEST_P(ASTMatchersTest, ParenType) {
1723   EXPECT_TRUE(
1724       matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
1725   EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
1726 
1727   EXPECT_TRUE(matches(
1728       "int (*ptr_to_func)(int);",
1729       varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1730   EXPECT_TRUE(notMatches(
1731       "int (*ptr_to_array)[4];",
1732       varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1733 }
1734 
1735 TEST_P(ASTMatchersTest, PointerType) {
1736   // FIXME: Reactive when these tests can be more specific (not matching
1737   // implicit code on certain platforms), likely when we have hasDescendant for
1738   // Types/TypeLocs.
1739   // EXPECT_TRUE(matchAndVerifyResultTrue(
1740   //    "int* a;",
1741   //    pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
1742   //    std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1743   // EXPECT_TRUE(matchAndVerifyResultTrue(
1744   //    "int* a;",
1745   //    pointerTypeLoc().bind("loc"),
1746   //    std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1747   EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(qualType())))));
1748   EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(pointerType())))));
1749   EXPECT_TRUE(matches("int* b; int* * const a = &b;",
1750                       loc(qualType(isConstQualified(), pointerType()))));
1751 
1752   StringRef Fragment = "int *ptr;";
1753   EXPECT_TRUE(notMatches(Fragment,
1754                          varDecl(hasName("ptr"), hasType(blockPointerType()))));
1755   EXPECT_TRUE(notMatches(
1756       Fragment, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1757   EXPECT_TRUE(
1758       matches(Fragment, varDecl(hasName("ptr"), hasType(pointerType()))));
1759   EXPECT_TRUE(
1760       notMatches(Fragment, varDecl(hasName("ptr"), hasType(referenceType()))));
1761 }
1762 
1763 TEST_P(ASTMatchersTest, PointerType_CXX) {
1764   if (!GetParam().isCXX()) {
1765     return;
1766   }
1767   StringRef Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
1768   EXPECT_TRUE(notMatches(Fragment,
1769                          varDecl(hasName("ptr"), hasType(blockPointerType()))));
1770   EXPECT_TRUE(
1771       matches(Fragment, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1772   EXPECT_TRUE(
1773       notMatches(Fragment, varDecl(hasName("ptr"), hasType(pointerType()))));
1774   EXPECT_TRUE(
1775       notMatches(Fragment, varDecl(hasName("ptr"), hasType(referenceType()))));
1776   EXPECT_TRUE(notMatches(
1777       Fragment, varDecl(hasName("ptr"), hasType(lValueReferenceType()))));
1778   EXPECT_TRUE(notMatches(
1779       Fragment, varDecl(hasName("ptr"), hasType(rValueReferenceType()))));
1780 
1781   Fragment = "int a; int &ref = a;";
1782   EXPECT_TRUE(notMatches(Fragment,
1783                          varDecl(hasName("ref"), hasType(blockPointerType()))));
1784   EXPECT_TRUE(notMatches(
1785       Fragment, varDecl(hasName("ref"), hasType(memberPointerType()))));
1786   EXPECT_TRUE(
1787       notMatches(Fragment, varDecl(hasName("ref"), hasType(pointerType()))));
1788   EXPECT_TRUE(
1789       matches(Fragment, varDecl(hasName("ref"), hasType(referenceType()))));
1790   EXPECT_TRUE(matches(Fragment,
1791                       varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1792   EXPECT_TRUE(notMatches(
1793       Fragment, varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1794 }
1795 
1796 TEST_P(ASTMatchersTest, PointerType_CXX11) {
1797   if (!GetParam().isCXX11OrLater()) {
1798     return;
1799   }
1800   StringRef Fragment = "int &&ref = 2;";
1801   EXPECT_TRUE(notMatches(Fragment,
1802                          varDecl(hasName("ref"), hasType(blockPointerType()))));
1803   EXPECT_TRUE(notMatches(
1804       Fragment, varDecl(hasName("ref"), hasType(memberPointerType()))));
1805   EXPECT_TRUE(
1806       notMatches(Fragment, varDecl(hasName("ref"), hasType(pointerType()))));
1807   EXPECT_TRUE(
1808       matches(Fragment, varDecl(hasName("ref"), hasType(referenceType()))));
1809   EXPECT_TRUE(notMatches(
1810       Fragment, varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1811   EXPECT_TRUE(matches(Fragment,
1812                       varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1813 }
1814 
1815 TEST_P(ASTMatchersTest, AutoRefTypes) {
1816   if (!GetParam().isCXX11OrLater()) {
1817     return;
1818   }
1819 
1820   StringRef Fragment = "auto a = 1;"
1821                        "auto b = a;"
1822                        "auto &c = a;"
1823                        "auto &&d = c;"
1824                        "auto &&e = 2;";
1825   EXPECT_TRUE(
1826       notMatches(Fragment, varDecl(hasName("a"), hasType(referenceType()))));
1827   EXPECT_TRUE(
1828       notMatches(Fragment, varDecl(hasName("b"), hasType(referenceType()))));
1829   EXPECT_TRUE(
1830       matches(Fragment, varDecl(hasName("c"), hasType(referenceType()))));
1831   EXPECT_TRUE(
1832       matches(Fragment, varDecl(hasName("c"), hasType(lValueReferenceType()))));
1833   EXPECT_TRUE(notMatches(
1834       Fragment, varDecl(hasName("c"), hasType(rValueReferenceType()))));
1835   EXPECT_TRUE(
1836       matches(Fragment, varDecl(hasName("d"), hasType(referenceType()))));
1837   EXPECT_TRUE(
1838       matches(Fragment, varDecl(hasName("d"), hasType(lValueReferenceType()))));
1839   EXPECT_TRUE(notMatches(
1840       Fragment, varDecl(hasName("d"), hasType(rValueReferenceType()))));
1841   EXPECT_TRUE(
1842       matches(Fragment, varDecl(hasName("e"), hasType(referenceType()))));
1843   EXPECT_TRUE(notMatches(
1844       Fragment, varDecl(hasName("e"), hasType(lValueReferenceType()))));
1845   EXPECT_TRUE(
1846       matches(Fragment, varDecl(hasName("e"), hasType(rValueReferenceType()))));
1847 }
1848 
1849 TEST_P(ASTMatchersTest, EnumType) {
1850   EXPECT_TRUE(
1851       matches("enum Color { Green }; enum Color color;", loc(enumType())));
1852 }
1853 
1854 TEST_P(ASTMatchersTest, EnumType_CXX) {
1855   if (!GetParam().isCXX()) {
1856     return;
1857   }
1858   EXPECT_TRUE(matches("enum Color { Green }; Color color;", loc(enumType())));
1859 }
1860 
1861 TEST_P(ASTMatchersTest, EnumType_CXX11) {
1862   if (!GetParam().isCXX11OrLater()) {
1863     return;
1864   }
1865   EXPECT_TRUE(
1866       matches("enum class Color { Green }; Color color;", loc(enumType())));
1867 }
1868 
1869 TEST_P(ASTMatchersTest, PointerType_MatchesPointersToConstTypes) {
1870   EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1871   EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1872   EXPECT_TRUE(matches("int b; const int * a = &b;",
1873                       loc(pointerType(pointee(builtinType())))));
1874   EXPECT_TRUE(matches("int b; const int * a = &b;",
1875                       pointerType(pointee(builtinType()))));
1876 }
1877 
1878 TEST_P(ASTMatchersTest, TypedefType) {
1879   EXPECT_TRUE(matches("typedef int X; X a;",
1880                       varDecl(hasName("a"), hasType(elaboratedType(
1881                                                 namesType(typedefType()))))));
1882 }
1883 
1884 TEST_P(ASTMatchersTest, MacroQualifiedType) {
1885   EXPECT_TRUE(matches(
1886       R"(
1887         #define CDECL __attribute__((cdecl))
1888         typedef void (CDECL *X)();
1889       )",
1890       typedefDecl(hasType(pointerType(pointee(macroQualifiedType()))))));
1891   EXPECT_TRUE(notMatches(
1892       R"(
1893         typedef void (__attribute__((cdecl)) *Y)();
1894       )",
1895       typedefDecl(hasType(pointerType(pointee(macroQualifiedType()))))));
1896 }
1897 
1898 TEST_P(ASTMatchersTest, TemplateSpecializationType) {
1899   if (!GetParam().isCXX()) {
1900     return;
1901   }
1902   EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
1903                       templateSpecializationType()));
1904 }
1905 
1906 TEST_P(ASTMatchersTest, DeducedTemplateSpecializationType) {
1907   if (!GetParam().isCXX17OrLater()) {
1908     return;
1909   }
1910   EXPECT_TRUE(
1911       matches("template <typename T> class A{ public: A(T) {} }; A a(1);",
1912               deducedTemplateSpecializationType()));
1913 }
1914 
1915 TEST_P(ASTMatchersTest, DependentNameType) {
1916   if (!GetParam().isCXX()) {
1917     return;
1918   }
1919 
1920   EXPECT_TRUE(matches(
1921       R"(
1922         template <typename T> struct declToImport {
1923           typedef typename T::type dependent_name;
1924         };
1925       )",
1926       dependentNameType()));
1927 }
1928 
1929 TEST_P(ASTMatchersTest, DependentTemplateSpecializationType) {
1930   if (!GetParam().isCXX()) {
1931     return;
1932   }
1933 
1934   EXPECT_TRUE(matches(
1935       R"(
1936         template<typename T> struct A;
1937         template<typename T> struct declToImport {
1938           typename A<T>::template B<T> a;
1939         };
1940       )",
1941       dependentTemplateSpecializationType()));
1942 }
1943 
1944 TEST_P(ASTMatchersTest, RecordType) {
1945   EXPECT_TRUE(matches("struct S {}; struct S s;",
1946                       recordType(hasDeclaration(recordDecl(hasName("S"))))));
1947   EXPECT_TRUE(notMatches("int i;",
1948                          recordType(hasDeclaration(recordDecl(hasName("S"))))));
1949 }
1950 
1951 TEST_P(ASTMatchersTest, RecordType_CXX) {
1952   if (!GetParam().isCXX()) {
1953     return;
1954   }
1955   EXPECT_TRUE(matches("class C {}; C c;", recordType()));
1956   EXPECT_TRUE(matches("struct S {}; S s;",
1957                       recordType(hasDeclaration(recordDecl(hasName("S"))))));
1958 }
1959 
1960 TEST_P(ASTMatchersTest, ElaboratedType) {
1961   if (!GetParam().isCXX()) {
1962     // FIXME: Add a test for `elaboratedType()` that does not depend on C++.
1963     return;
1964   }
1965   EXPECT_TRUE(matches("namespace N {"
1966                       "  namespace M {"
1967                       "    class D {};"
1968                       "  }"
1969                       "}"
1970                       "N::M::D d;",
1971                       elaboratedType()));
1972   EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
1973   EXPECT_TRUE(matches("class C {}; C c;", elaboratedType()));
1974 }
1975 
1976 TEST_P(ASTMatchersTest, SubstTemplateTypeParmType) {
1977   if (!GetParam().isCXX()) {
1978     return;
1979   }
1980   StringRef code = "template <typename T>"
1981                    "int F() {"
1982                    "  return 1 + T();"
1983                    "}"
1984                    "int i = F<int>();";
1985   EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
1986                                  expr(hasType(substTemplateTypeParmType()))))));
1987   EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
1988                                 expr(hasType(substTemplateTypeParmType()))))));
1989 }
1990 
1991 TEST_P(ASTMatchersTest, NestedNameSpecifier) {
1992   if (!GetParam().isCXX()) {
1993     return;
1994   }
1995   EXPECT_TRUE(
1996       matches("namespace ns { struct A {}; } ns::A a;", nestedNameSpecifier()));
1997   EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
1998                       nestedNameSpecifier()));
1999   EXPECT_TRUE(
2000       matches("struct A { void f(); }; void A::f() {}", nestedNameSpecifier()));
2001   EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
2002                       nestedNameSpecifier()));
2003 
2004   EXPECT_TRUE(matches("struct A { static void f() {} }; void g() { A::f(); }",
2005                       nestedNameSpecifier()));
2006   EXPECT_TRUE(
2007       notMatches("struct A { static void f() {} }; void g(A* a) { a->f(); }",
2008                  nestedNameSpecifier()));
2009 }
2010 
2011 TEST_P(ASTMatchersTest, Attr) {
2012   // Windows adds some implicit attributes.
2013   bool AutomaticAttributes = StringRef(GetParam().Target).contains("win32");
2014   if (GetParam().isCXX11OrLater()) {
2015     EXPECT_TRUE(matches("struct [[clang::warn_unused_result]] F{};", attr()));
2016 
2017     // Unknown attributes are not parsed into an AST node.
2018     if (!AutomaticAttributes) {
2019       EXPECT_TRUE(notMatches("int x [[unknownattr]];", attr()));
2020     }
2021   }
2022   if (GetParam().isCXX17OrLater()) {
2023     EXPECT_TRUE(matches("struct [[nodiscard]] F{};", attr()));
2024   }
2025   EXPECT_TRUE(matches("int x(int * __attribute__((nonnull)) );", attr()));
2026   if (!AutomaticAttributes) {
2027     EXPECT_TRUE(notMatches("struct F{}; int x(int *);", attr()));
2028     // Some known attributes are not parsed into an AST node.
2029     EXPECT_TRUE(notMatches("typedef int x __attribute__((ext_vector_type(1)));",
2030                            attr()));
2031   }
2032 }
2033 
2034 TEST_P(ASTMatchersTest, NullStmt) {
2035   EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
2036   EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
2037 }
2038 
2039 TEST_P(ASTMatchersTest, NamespaceAliasDecl) {
2040   if (!GetParam().isCXX()) {
2041     return;
2042   }
2043   EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
2044                       namespaceAliasDecl(hasName("alias"))));
2045 }
2046 
2047 TEST_P(ASTMatchersTest, NestedNameSpecifier_MatchesTypes) {
2048   if (!GetParam().isCXX()) {
2049     return;
2050   }
2051   NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
2052       specifiesType(hasDeclaration(recordDecl(hasName("A")))));
2053   EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
2054   EXPECT_TRUE(
2055       matches("struct A { struct B { struct C {}; }; }; A::B::C c;", Matcher));
2056   EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
2057 }
2058 
2059 TEST_P(ASTMatchersTest, NestedNameSpecifier_MatchesNamespaceDecls) {
2060   if (!GetParam().isCXX()) {
2061     return;
2062   }
2063   NestedNameSpecifierMatcher Matcher =
2064       nestedNameSpecifier(specifiesNamespace(hasName("ns")));
2065   EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
2066   EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
2067   EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
2068 }
2069 
2070 TEST_P(ASTMatchersTest,
2071        NestedNameSpecifier_MatchesNestedNameSpecifierPrefixes) {
2072   if (!GetParam().isCXX()) {
2073     return;
2074   }
2075   EXPECT_TRUE(matches(
2076       "struct A { struct B { struct C {}; }; }; A::B::C c;",
2077       nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
2078   EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
2079                       nestedNameSpecifierLoc(hasPrefix(specifiesTypeLoc(
2080                           loc(qualType(asString("struct A"))))))));
2081   EXPECT_TRUE(matches(
2082       "namespace N { struct A { struct B { struct C {}; }; }; } N::A::B::C c;",
2083       nestedNameSpecifierLoc(hasPrefix(
2084           specifiesTypeLoc(loc(qualType(asString("struct N::A"))))))));
2085 }
2086 
2087 template <typename T>
2088 class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
2089 public:
2090   bool run(const BoundNodes *Nodes, ASTContext *Context) override {
2091     const T *Node = Nodes->getNodeAs<T>("");
2092     return verify(*Nodes, *Context, Node);
2093   }
2094 
2095   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
2096     // Use the original typed pointer to verify we can pass pointers to subtypes
2097     // to equalsNode.
2098     const T *TypedNode = cast<T>(Node);
2099     return selectFirst<T>(
2100                "", match(stmt(hasParent(
2101                              stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
2102                          *Node, Context)) != nullptr;
2103   }
2104   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
2105     // Use the original typed pointer to verify we can pass pointers to subtypes
2106     // to equalsNode.
2107     const T *TypedNode = cast<T>(Node);
2108     return selectFirst<T>(
2109                "", match(decl(hasParent(
2110                              decl(has(decl(equalsNode(TypedNode)))).bind(""))),
2111                          *Node, Context)) != nullptr;
2112   }
2113   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
2114     // Use the original typed pointer to verify we can pass pointers to subtypes
2115     // to equalsNode.
2116     const T *TypedNode = cast<T>(Node);
2117     const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
2118     return selectFirst<T>(
2119                "", match(fieldDecl(hasParent(decl(has(fieldDecl(
2120                              hasType(type(equalsNode(TypedNode)).bind(""))))))),
2121                          *Dec, Context)) != nullptr;
2122   }
2123 };
2124 
2125 TEST_P(ASTMatchersTest, IsEqualTo_MatchesNodesByIdentity) {
2126   EXPECT_TRUE(matchAndVerifyResultTrue(
2127       "void f() { if (1) if(1) {} }", ifStmt().bind(""),
2128       std::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>()));
2129 }
2130 
2131 TEST_P(ASTMatchersTest, IsEqualTo_MatchesNodesByIdentity_Cxx) {
2132   if (!GetParam().isCXX()) {
2133     return;
2134   }
2135   EXPECT_TRUE(matchAndVerifyResultTrue(
2136       "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
2137       std::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>()));
2138   EXPECT_TRUE(matchAndVerifyResultTrue(
2139       "class X { class Y {} y; };",
2140       fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
2141       std::make_unique<VerifyAncestorHasChildIsEqual<Type>>()));
2142 }
2143 
2144 TEST_P(ASTMatchersTest, TypedefDecl) {
2145   EXPECT_TRUE(matches("typedef int typedefDeclTest;",
2146                       typedefDecl(hasName("typedefDeclTest"))));
2147 }
2148 
2149 TEST_P(ASTMatchersTest, TypedefDecl_Cxx) {
2150   if (!GetParam().isCXX11OrLater()) {
2151     return;
2152   }
2153   EXPECT_TRUE(notMatches("using typedefDeclTest = int;",
2154                          typedefDecl(hasName("typedefDeclTest"))));
2155 }
2156 
2157 TEST_P(ASTMatchersTest, TypeAliasDecl) {
2158   EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
2159                          typeAliasDecl(hasName("typeAliasTest"))));
2160 }
2161 
2162 TEST_P(ASTMatchersTest, TypeAliasDecl_CXX) {
2163   if (!GetParam().isCXX11OrLater()) {
2164     return;
2165   }
2166   EXPECT_TRUE(matches("using typeAliasTest = int;",
2167                       typeAliasDecl(hasName("typeAliasTest"))));
2168 }
2169 
2170 TEST_P(ASTMatchersTest, TypedefNameDecl) {
2171   EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
2172                       typedefNameDecl(hasName("typedefNameDeclTest1"))));
2173 }
2174 
2175 TEST_P(ASTMatchersTest, TypedefNameDecl_CXX) {
2176   if (!GetParam().isCXX11OrLater()) {
2177     return;
2178   }
2179   EXPECT_TRUE(matches("using typedefNameDeclTest = int;",
2180                       typedefNameDecl(hasName("typedefNameDeclTest"))));
2181 }
2182 
2183 TEST_P(ASTMatchersTest, TypeAliasTemplateDecl) {
2184   if (!GetParam().isCXX11OrLater()) {
2185     return;
2186   }
2187   StringRef Code = R"(
2188     template <typename T>
2189     class X { T t; };
2190 
2191     template <typename T>
2192     using typeAliasTemplateDecl = X<T>;
2193 
2194     using typeAliasDecl = X<int>;
2195   )";
2196   EXPECT_TRUE(
2197       matches(Code, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl"))));
2198   EXPECT_TRUE(
2199       notMatches(Code, typeAliasTemplateDecl(hasName("typeAliasDecl"))));
2200 }
2201 
2202 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_BindsToConstIntVarDecl) {
2203   EXPECT_TRUE(matches("const int x = 0;",
2204                       qualifiedTypeLoc(loc(asString("const int")))));
2205 }
2206 
2207 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_BindsToConstIntFunctionDecl) {
2208   EXPECT_TRUE(matches("const int f() { return 5; }",
2209                       qualifiedTypeLoc(loc(asString("const int")))));
2210 }
2211 
2212 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_DoesNotBindToUnqualifiedVarDecl) {
2213   EXPECT_TRUE(notMatches("int x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2214 }
2215 
2216 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_IntDoesNotBindToConstIntDecl) {
2217   EXPECT_TRUE(
2218       notMatches("const int x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2219 }
2220 
2221 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_IntDoesNotBindToConstFloatDecl) {
2222   EXPECT_TRUE(
2223       notMatches("const float x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2224 }
2225 
2226 TEST_P(ASTMatchersTest, PointerTypeLocTest_BindsToAnyPointerTypeLoc) {
2227   auto matcher = varDecl(hasName("x"), hasTypeLoc(pointerTypeLoc()));
2228   EXPECT_TRUE(matches("int* x;", matcher));
2229   EXPECT_TRUE(matches("float* x;", matcher));
2230   EXPECT_TRUE(matches("char* x;", matcher));
2231   EXPECT_TRUE(matches("void* x;", matcher));
2232 }
2233 
2234 TEST_P(ASTMatchersTest, PointerTypeLocTest_DoesNotBindToNonPointerTypeLoc) {
2235   auto matcher = varDecl(hasName("x"), hasTypeLoc(pointerTypeLoc()));
2236   EXPECT_TRUE(notMatches("int x;", matcher));
2237   EXPECT_TRUE(notMatches("float x;", matcher));
2238   EXPECT_TRUE(notMatches("char x;", matcher));
2239 }
2240 
2241 TEST_P(ASTMatchersTest, ReferenceTypeLocTest_BindsToAnyReferenceTypeLoc) {
2242   if (!GetParam().isCXX()) {
2243     return;
2244   }
2245   auto matcher = varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2246   EXPECT_TRUE(matches("int rr = 3; int& r = rr;", matcher));
2247   EXPECT_TRUE(matches("int rr = 3; auto& r = rr;", matcher));
2248   EXPECT_TRUE(matches("int rr = 3; const int& r = rr;", matcher));
2249   EXPECT_TRUE(matches("float rr = 3.0; float& r = rr;", matcher));
2250   EXPECT_TRUE(matches("char rr = 'a'; char& r = rr;", matcher));
2251 }
2252 
2253 TEST_P(ASTMatchersTest, ReferenceTypeLocTest_DoesNotBindToNonReferenceTypeLoc) {
2254   auto matcher = varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2255   EXPECT_TRUE(notMatches("int r;", matcher));
2256   EXPECT_TRUE(notMatches("int r = 3;", matcher));
2257   EXPECT_TRUE(notMatches("const int r = 3;", matcher));
2258   EXPECT_TRUE(notMatches("int* r;", matcher));
2259   EXPECT_TRUE(notMatches("float r;", matcher));
2260   EXPECT_TRUE(notMatches("char r;", matcher));
2261 }
2262 
2263 TEST_P(ASTMatchersTest, ReferenceTypeLocTest_BindsToAnyRvalueReferenceTypeLoc) {
2264   if (!GetParam().isCXX()) {
2265     return;
2266   }
2267   auto matcher = varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2268   EXPECT_TRUE(matches("int&& r = 3;", matcher));
2269   EXPECT_TRUE(matches("auto&& r = 3;", matcher));
2270   EXPECT_TRUE(matches("float&& r = 3.0;", matcher));
2271 }
2272 
2273 TEST_P(ASTMatchersTest,
2274        TemplateSpecializationTypeLocTest_BindsToVarDeclTemplateSpecialization) {
2275   if (!GetParam().isCXX()) {
2276     return;
2277   }
2278   EXPECT_TRUE(matches(
2279       "template <typename T> class C {}; C<char> var;",
2280       varDecl(hasName("var"), hasTypeLoc(elaboratedTypeLoc(hasNamedTypeLoc(
2281                                   templateSpecializationTypeLoc()))))));
2282 }
2283 
2284 TEST_P(
2285     ASTMatchersTest,
2286     TemplateSpecializationTypeLocTest_DoesNotBindToNonTemplateSpecialization) {
2287   if (!GetParam().isCXX()) {
2288     return;
2289   }
2290   EXPECT_TRUE(notMatches(
2291       "class C {}; C var;",
2292       varDecl(hasName("var"), hasTypeLoc(templateSpecializationTypeLoc()))));
2293 }
2294 
2295 TEST_P(ASTMatchersTest,
2296        ElaboratedTypeLocTest_BindsToElaboratedObjectDeclaration) {
2297   if (!GetParam().isCXX()) {
2298     return;
2299   }
2300   EXPECT_TRUE(matches("class C {}; class C c;",
2301                       varDecl(hasName("c"), hasTypeLoc(elaboratedTypeLoc()))));
2302 }
2303 
2304 TEST_P(ASTMatchersTest,
2305        ElaboratedTypeLocTest_BindsToNamespaceElaboratedObjectDeclaration) {
2306   if (!GetParam().isCXX()) {
2307     return;
2308   }
2309   EXPECT_TRUE(matches("namespace N { class D {}; } N::D d;",
2310                       varDecl(hasName("d"), hasTypeLoc(elaboratedTypeLoc()))));
2311 }
2312 
2313 TEST_P(ASTMatchersTest,
2314        ElaboratedTypeLocTest_BindsToElaboratedStructDeclaration) {
2315   EXPECT_TRUE(matches("struct s {}; struct s ss;",
2316                       varDecl(hasName("ss"), hasTypeLoc(elaboratedTypeLoc()))));
2317 }
2318 
2319 TEST_P(ASTMatchersTest,
2320        ElaboratedTypeLocTest_BindsToBareElaboratedObjectDeclaration) {
2321   if (!GetParam().isCXX()) {
2322     return;
2323   }
2324   EXPECT_TRUE(matches("class C {}; C c;",
2325                       varDecl(hasName("c"), hasTypeLoc(elaboratedTypeLoc()))));
2326 }
2327 
2328 TEST_P(
2329     ASTMatchersTest,
2330     ElaboratedTypeLocTest_DoesNotBindToNamespaceNonElaboratedObjectDeclaration) {
2331   if (!GetParam().isCXX()) {
2332     return;
2333   }
2334   EXPECT_TRUE(matches("namespace N { class D {}; } using N::D; D d;",
2335                       varDecl(hasName("d"), hasTypeLoc(elaboratedTypeLoc()))));
2336 }
2337 
2338 TEST_P(ASTMatchersTest,
2339        ElaboratedTypeLocTest_BindsToBareElaboratedStructDeclaration) {
2340   if (!GetParam().isCXX()) {
2341     return;
2342   }
2343   EXPECT_TRUE(matches("struct s {}; s ss;",
2344                       varDecl(hasName("ss"), hasTypeLoc(elaboratedTypeLoc()))));
2345 }
2346 
2347 TEST_P(ASTMatchersTest, LambdaCaptureTest) {
2348   if (!GetParam().isCXX11OrLater()) {
2349     return;
2350   }
2351   EXPECT_TRUE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
2352                       lambdaExpr(hasAnyCapture(lambdaCapture()))));
2353 }
2354 
2355 TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureOfVarDecl) {
2356   if (!GetParam().isCXX11OrLater()) {
2357     return;
2358   }
2359   auto matcher = lambdaExpr(
2360       hasAnyCapture(lambdaCapture(capturesVar(varDecl(hasName("cc"))))));
2361   EXPECT_TRUE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
2362                       matcher));
2363   EXPECT_TRUE(matches("int main() { int cc; auto f = [&cc](){ return cc; }; }",
2364                       matcher));
2365   EXPECT_TRUE(
2366       matches("int main() { int cc; auto f = [=](){ return cc; }; }", matcher));
2367   EXPECT_TRUE(
2368       matches("int main() { int cc; auto f = [&](){ return cc; }; }", matcher));
2369   EXPECT_TRUE(matches(
2370       "void f(int a) { int cc[a]; auto f = [&](){ return cc;}; }", matcher));
2371 }
2372 
2373 TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureWithInitializer) {
2374   if (!GetParam().isCXX14OrLater()) {
2375     return;
2376   }
2377   auto matcher = lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(
2378       varDecl(hasName("cc"), hasInitializer(integerLiteral(equals(1))))))));
2379   EXPECT_TRUE(
2380       matches("int main() { auto lambda = [cc = 1] {return cc;}; }", matcher));
2381   EXPECT_TRUE(
2382       matches("int main() { int cc = 2; auto lambda = [cc = 1] {return cc;}; }",
2383               matcher));
2384 }
2385 
2386 TEST_P(ASTMatchersTest, LambdaCaptureTest_DoesNotBindToCaptureOfVarDecl) {
2387   if (!GetParam().isCXX11OrLater()) {
2388     return;
2389   }
2390   auto matcher = lambdaExpr(
2391       hasAnyCapture(lambdaCapture(capturesVar(varDecl(hasName("cc"))))));
2392   EXPECT_FALSE(matches("int main() { auto f = [](){ return 5; }; }", matcher));
2393   EXPECT_FALSE(matches("int main() { int xx; auto f = [xx](){ return xx; }; }",
2394                        matcher));
2395 }
2396 
2397 TEST_P(ASTMatchersTest,
2398        LambdaCaptureTest_DoesNotBindToCaptureWithInitializerAndDifferentName) {
2399   if (!GetParam().isCXX14OrLater()) {
2400     return;
2401   }
2402   EXPECT_FALSE(matches(
2403       "int main() { auto lambda = [xx = 1] {return xx;}; }",
2404       lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(varDecl(
2405           hasName("cc"), hasInitializer(integerLiteral(equals(1))))))))));
2406 }
2407 
2408 TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureOfReferenceType) {
2409   if (!GetParam().isCXX20OrLater()) {
2410     return;
2411   }
2412   auto matcher = lambdaExpr(hasAnyCapture(
2413       lambdaCapture(capturesVar(varDecl(hasType(referenceType()))))));
2414   EXPECT_TRUE(matches("template <class ...T> void f(T &...args) {"
2415                       "  [&...args = args] () mutable {"
2416                       "  }();"
2417                       "}"
2418                       "int main() {"
2419                       "  int a;"
2420                       "  f(a);"
2421                       "}", matcher));
2422   EXPECT_FALSE(matches("template <class ...T> void f(T &...args) {"
2423                        "  [...args = args] () mutable {"
2424                        "  }();"
2425                        "}"
2426                        "int main() {"
2427                        "  int a;"
2428                        "  f(a);"
2429                        "}", matcher));
2430 }
2431 
2432 TEST_P(ASTMatchersTest, IsDerivedFromRecursion) {
2433   if (!GetParam().isCXX11OrLater())
2434     return;
2435 
2436   // Check we don't crash on cycles in the traversal and inheritance hierarchy.
2437   // Clang will normally enforce there are no cycles, but matchers opted to
2438   // traverse primary template for dependent specializations, spuriously
2439   // creating the cycles.
2440   DeclarationMatcher matcher = cxxRecordDecl(isDerivedFrom("X"));
2441   EXPECT_TRUE(notMatches(R"cpp(
2442       template <typename T1, typename T2>
2443       struct M;
2444 
2445       template <typename T1>
2446       struct M<T1, void> {};
2447 
2448       template <typename T1, typename T2>
2449       struct L : M<T1, T2> {};
2450 
2451       template <typename T1, typename T2>
2452       struct M : L<M<T1, T2>, M<T1, T2>> {};
2453   )cpp",
2454                          matcher));
2455 
2456   // Check the running time is not exponential. The number of subojects to
2457   // traverse grows as fibonacci numbers even though the number of bases to
2458   // traverse is quadratic.
2459   // The test will hang if implementation of matchers traverses all subojects.
2460   EXPECT_TRUE(notMatches(R"cpp(
2461     template <class T> struct A0 {};
2462     template <class T> struct A1 : A0<T> {};
2463     template <class T> struct A2 : A1<T>, A0<T> {};
2464     template <class T> struct A3 : A2<T>, A1<T> {};
2465     template <class T> struct A4 : A3<T>, A2<T> {};
2466     template <class T> struct A5 : A4<T>, A3<T> {};
2467     template <class T> struct A6 : A5<T>, A4<T> {};
2468     template <class T> struct A7 : A6<T>, A5<T> {};
2469     template <class T> struct A8 : A7<T>, A6<T> {};
2470     template <class T> struct A9 : A8<T>, A7<T> {};
2471     template <class T> struct A10 : A9<T>, A8<T> {};
2472     template <class T> struct A11 : A10<T>, A9<T> {};
2473     template <class T> struct A12 : A11<T>, A10<T> {};
2474     template <class T> struct A13 : A12<T>, A11<T> {};
2475     template <class T> struct A14 : A13<T>, A12<T> {};
2476     template <class T> struct A15 : A14<T>, A13<T> {};
2477     template <class T> struct A16 : A15<T>, A14<T> {};
2478     template <class T> struct A17 : A16<T>, A15<T> {};
2479     template <class T> struct A18 : A17<T>, A16<T> {};
2480     template <class T> struct A19 : A18<T>, A17<T> {};
2481     template <class T> struct A20 : A19<T>, A18<T> {};
2482     template <class T> struct A21 : A20<T>, A19<T> {};
2483     template <class T> struct A22 : A21<T>, A20<T> {};
2484     template <class T> struct A23 : A22<T>, A21<T> {};
2485     template <class T> struct A24 : A23<T>, A22<T> {};
2486     template <class T> struct A25 : A24<T>, A23<T> {};
2487     template <class T> struct A26 : A25<T>, A24<T> {};
2488     template <class T> struct A27 : A26<T>, A25<T> {};
2489     template <class T> struct A28 : A27<T>, A26<T> {};
2490     template <class T> struct A29 : A28<T>, A27<T> {};
2491     template <class T> struct A30 : A29<T>, A28<T> {};
2492     template <class T> struct A31 : A30<T>, A29<T> {};
2493     template <class T> struct A32 : A31<T>, A30<T> {};
2494     template <class T> struct A33 : A32<T>, A31<T> {};
2495     template <class T> struct A34 : A33<T>, A32<T> {};
2496     template <class T> struct A35 : A34<T>, A33<T> {};
2497     template <class T> struct A36 : A35<T>, A34<T> {};
2498     template <class T> struct A37 : A36<T>, A35<T> {};
2499     template <class T> struct A38 : A37<T>, A36<T> {};
2500     template <class T> struct A39 : A38<T>, A37<T> {};
2501     template <class T> struct A40 : A39<T>, A38<T> {};
2502 )cpp",
2503                          matcher));
2504 }
2505 
2506 TEST(ASTMatchersTestObjC, ObjCMessageCalees) {
2507   StatementMatcher MessagingFoo =
2508       objcMessageExpr(callee(objcMethodDecl(hasName("foo"))));
2509 
2510   EXPECT_TRUE(matchesObjC("@interface I"
2511                           "+ (void)foo;"
2512                           "@end\n"
2513                           "int main() {"
2514                           "  [I foo];"
2515                           "}",
2516                           MessagingFoo));
2517   EXPECT_TRUE(notMatchesObjC("@interface I"
2518                              "+ (void)foo;"
2519                              "+ (void)bar;"
2520                              "@end\n"
2521                              "int main() {"
2522                              "  [I bar];"
2523                              "}",
2524                              MessagingFoo));
2525   EXPECT_TRUE(matchesObjC("@interface I"
2526                           "- (void)foo;"
2527                           "- (void)bar;"
2528                           "@end\n"
2529                           "int main() {"
2530                           "  I *i;"
2531                           "  [i foo];"
2532                           "}",
2533                           MessagingFoo));
2534   EXPECT_TRUE(notMatchesObjC("@interface I"
2535                              "- (void)foo;"
2536                              "- (void)bar;"
2537                              "@end\n"
2538                              "int main() {"
2539                              "  I *i;"
2540                              "  [i bar];"
2541                              "}",
2542                              MessagingFoo));
2543 }
2544 
2545 TEST(ASTMatchersTestObjC, ObjCMessageExpr) {
2546   // Don't find ObjCMessageExpr where none are present.
2547   EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
2548 
2549   StringRef Objc1String = "@interface Str "
2550                           " - (Str *)uppercaseString;"
2551                           "@end "
2552                           "@interface foo "
2553                           "- (void)contents;"
2554                           "- (void)meth:(Str *)text;"
2555                           "@end "
2556                           " "
2557                           "@implementation foo "
2558                           "- (void) meth:(Str *)text { "
2559                           "  [self contents];"
2560                           "  Str *up = [text uppercaseString];"
2561                           "} "
2562                           "@end ";
2563   EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(anything())));
2564   EXPECT_TRUE(matchesObjC(Objc1String,
2565                           objcMessageExpr(hasAnySelector({"contents", "meth:"}))
2566 
2567                               ));
2568   EXPECT_TRUE(
2569       matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"))));
2570   EXPECT_TRUE(matchesObjC(
2571       Objc1String, objcMessageExpr(hasAnySelector("contents", "contentsA"))));
2572   EXPECT_FALSE(matchesObjC(
2573       Objc1String, objcMessageExpr(hasAnySelector("contentsB", "contentsC"))));
2574   EXPECT_TRUE(
2575       matchesObjC(Objc1String, objcMessageExpr(matchesSelector("cont*"))));
2576   EXPECT_FALSE(
2577       matchesObjC(Objc1String, objcMessageExpr(matchesSelector("?cont*"))));
2578   EXPECT_TRUE(
2579       notMatchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2580                                                   hasNullSelector())));
2581   EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2582                                                        hasUnarySelector())));
2583   EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2584                                                        numSelectorArgs(0))));
2585   EXPECT_TRUE(
2586       matchesObjC(Objc1String, objcMessageExpr(matchesSelector("uppercase*"),
2587                                                argumentCountIs(0))));
2588 }
2589 
2590 TEST(ASTMatchersTestObjC, ObjCStringLiteral) {
2591 
2592   StringRef Objc1String = "@interface NSObject "
2593                           "@end "
2594                           "@interface NSString "
2595                           "@end "
2596                           "@interface Test : NSObject "
2597                           "+ (void)someFunction:(NSString *)Desc; "
2598                           "@end "
2599                           "@implementation Test "
2600                           "+ (void)someFunction:(NSString *)Desc { "
2601                           "    return; "
2602                           "} "
2603                           "- (void) foo { "
2604                           "    [Test someFunction:@\"Ola!\"]; "
2605                           "}\n"
2606                           "@end ";
2607     EXPECT_TRUE(matchesObjC(Objc1String, objcStringLiteral()));
2608 }
2609 
2610 TEST(ASTMatchersTestObjC, ObjCDecls) {
2611   StringRef ObjCString = "@protocol Proto "
2612                          "- (void)protoDidThing; "
2613                          "@end "
2614                          "@interface Thing "
2615                          "@property int enabled; "
2616                          "@end "
2617                          "@interface Thing (ABC) "
2618                          "- (void)abc_doThing; "
2619                          "@end "
2620                          "@implementation Thing "
2621                          "{ id _ivar; } "
2622                          "- (void)anything {} "
2623                          "@end "
2624                          "@implementation Thing (ABC) "
2625                          "- (void)abc_doThing {} "
2626                          "@end ";
2627 
2628   EXPECT_TRUE(matchesObjC(ObjCString, objcProtocolDecl(hasName("Proto"))));
2629   EXPECT_TRUE(
2630       matchesObjC(ObjCString, objcImplementationDecl(hasName("Thing"))));
2631   EXPECT_TRUE(matchesObjC(ObjCString, objcCategoryDecl(hasName("ABC"))));
2632   EXPECT_TRUE(matchesObjC(ObjCString, objcCategoryImplDecl(hasName("ABC"))));
2633   EXPECT_TRUE(
2634       matchesObjC(ObjCString, objcMethodDecl(hasName("protoDidThing"))));
2635   EXPECT_TRUE(matchesObjC(ObjCString, objcMethodDecl(hasName("abc_doThing"))));
2636   EXPECT_TRUE(matchesObjC(ObjCString, objcMethodDecl(hasName("anything"))));
2637   EXPECT_TRUE(matchesObjC(ObjCString, objcIvarDecl(hasName("_ivar"))));
2638   EXPECT_TRUE(matchesObjC(ObjCString, objcPropertyDecl(hasName("enabled"))));
2639 }
2640 
2641 TEST(ASTMatchersTestObjC, ObjCExceptionStmts) {
2642   StringRef ObjCString = "void f(id obj) {"
2643                          "  @try {"
2644                          "    @throw obj;"
2645                          "  } @catch (...) {"
2646                          "  } @finally {}"
2647                          "}";
2648 
2649   EXPECT_TRUE(matchesObjC(ObjCString, objcTryStmt()));
2650   EXPECT_TRUE(matchesObjC(ObjCString, objcThrowStmt()));
2651   EXPECT_TRUE(matchesObjC(ObjCString, objcCatchStmt()));
2652   EXPECT_TRUE(matchesObjC(ObjCString, objcFinallyStmt()));
2653 }
2654 
2655 TEST(ASTMatchersTest, DecompositionDecl) {
2656   StringRef Code = R"cpp(
2657 void foo()
2658 {
2659     int arr[3];
2660     auto &[f, s, t] = arr;
2661 
2662     f = 42;
2663 }
2664   )cpp";
2665   EXPECT_TRUE(matchesConditionally(
2666       Code, decompositionDecl(hasBinding(0, bindingDecl(hasName("f")))), true,
2667       {"-std=c++17"}));
2668   EXPECT_FALSE(matchesConditionally(
2669       Code, decompositionDecl(hasBinding(42, bindingDecl(hasName("f")))), true,
2670       {"-std=c++17"}));
2671   EXPECT_FALSE(matchesConditionally(
2672       Code, decompositionDecl(hasBinding(0, bindingDecl(hasName("s")))), true,
2673       {"-std=c++17"}));
2674   EXPECT_TRUE(matchesConditionally(
2675       Code, decompositionDecl(hasBinding(1, bindingDecl(hasName("s")))), true,
2676       {"-std=c++17"}));
2677 
2678   EXPECT_TRUE(matchesConditionally(
2679       Code,
2680       bindingDecl(decl().bind("self"), hasName("f"),
2681                   forDecomposition(decompositionDecl(
2682                       hasAnyBinding(bindingDecl(equalsBoundNode("self")))))),
2683       true, {"-std=c++17"}));
2684 }
2685 
2686 TEST(ASTMatchersTestObjC, ObjCAutoreleasePoolStmt) {
2687   StringRef ObjCString = "void f() {"
2688                          "@autoreleasepool {"
2689                          "  int x = 1;"
2690                          "}"
2691                          "}";
2692   EXPECT_TRUE(matchesObjC(ObjCString, autoreleasePoolStmt()));
2693   StringRef ObjCStringNoPool = "void f() { int x = 1; }";
2694   EXPECT_FALSE(matchesObjC(ObjCStringNoPool, autoreleasePoolStmt()));
2695 }
2696 
2697 TEST(ASTMatchersTestOpenMP, OMPExecutableDirective) {
2698   auto Matcher = stmt(ompExecutableDirective());
2699 
2700   StringRef Source0 = R"(
2701 void x() {
2702 #pragma omp parallel
2703 ;
2704 })";
2705   EXPECT_TRUE(matchesWithOpenMP(Source0, Matcher));
2706 
2707   StringRef Source1 = R"(
2708 void x() {
2709 #pragma omp taskyield
2710 ;
2711 })";
2712   EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
2713 
2714   StringRef Source2 = R"(
2715 void x() {
2716 ;
2717 })";
2718   EXPECT_TRUE(notMatchesWithOpenMP(Source2, Matcher));
2719 }
2720 
2721 TEST(ASTMatchersTestOpenMP, OMPDefaultClause) {
2722   auto Matcher = ompExecutableDirective(hasAnyClause(ompDefaultClause()));
2723 
2724   StringRef Source0 = R"(
2725 void x() {
2726 ;
2727 })";
2728   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2729 
2730   StringRef Source1 = R"(
2731 void x() {
2732 #pragma omp parallel
2733 ;
2734 })";
2735   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
2736 
2737   StringRef Source2 = R"(
2738 void x() {
2739 #pragma omp parallel default(none)
2740 ;
2741 })";
2742   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
2743 
2744   StringRef Source3 = R"(
2745 void x() {
2746 #pragma omp parallel default(shared)
2747 ;
2748 })";
2749   EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
2750 
2751   StringRef Source4 = R"(
2752 void x() {
2753 #pragma omp parallel default(firstprivate)
2754 ;
2755 })";
2756   EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
2757 
2758   StringRef Source5 = R"(
2759 void x(int x) {
2760 #pragma omp parallel num_threads(x)
2761 ;
2762 })";
2763   EXPECT_TRUE(notMatchesWithOpenMP(Source5, Matcher));
2764 }
2765 
2766 TEST(ASTMatchersTest, Finder_DynamicOnlyAcceptsSomeMatchers) {
2767   MatchFinder Finder;
2768   EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
2769   EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
2770   EXPECT_TRUE(
2771       Finder.addDynamicMatcher(constantArrayType(hasSize(42)), nullptr));
2772 
2773   // Do not accept non-toplevel matchers.
2774   EXPECT_FALSE(Finder.addDynamicMatcher(isMain(), nullptr));
2775   EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
2776 }
2777 
2778 TEST(MatchFinderAPI, MatchesDynamic) {
2779   StringRef SourceCode = "struct A { void f() {} };";
2780   auto Matcher = functionDecl(isDefinition()).bind("method");
2781 
2782   auto astUnit = tooling::buildASTFromCode(SourceCode);
2783 
2784   auto GlobalBoundNodes = matchDynamic(Matcher, astUnit->getASTContext());
2785 
2786   EXPECT_EQ(GlobalBoundNodes.size(), 1u);
2787   EXPECT_EQ(GlobalBoundNodes[0].getMap().size(), 1u);
2788 
2789   auto GlobalMethodNode = GlobalBoundNodes[0].getNodeAs<FunctionDecl>("method");
2790   EXPECT_TRUE(GlobalMethodNode != nullptr);
2791 
2792   auto MethodBoundNodes =
2793       matchDynamic(Matcher, *GlobalMethodNode, astUnit->getASTContext());
2794   EXPECT_EQ(MethodBoundNodes.size(), 1u);
2795   EXPECT_EQ(MethodBoundNodes[0].getMap().size(), 1u);
2796 
2797   auto MethodNode = MethodBoundNodes[0].getNodeAs<FunctionDecl>("method");
2798   EXPECT_EQ(MethodNode, GlobalMethodNode);
2799 }
2800 
2801 static std::vector<TestClangConfig> allTestClangConfigs() {
2802   std::vector<TestClangConfig> all_configs;
2803   for (TestLanguage lang : {
2804 #define TESTLANGUAGE(lang, version, std_flag, version_index)                   \
2805   Lang_##lang##version,
2806 #include "clang/Testing/TestLanguage.def"
2807        }) {
2808     TestClangConfig config;
2809     config.Language = lang;
2810 
2811     // Use an unknown-unknown triple so we don't instantiate the full system
2812     // toolchain.  On Linux, instantiating the toolchain involves stat'ing
2813     // large portions of /usr/lib, and this slows down not only this test, but
2814     // all other tests, via contention in the kernel.
2815     //
2816     // FIXME: This is a hack to work around the fact that there's no way to do
2817     // the equivalent of runToolOnCodeWithArgs without instantiating a full
2818     // Driver.  We should consider having a function, at least for tests, that
2819     // invokes cc1.
2820     config.Target = "i386-unknown-unknown";
2821     all_configs.push_back(config);
2822 
2823     // Windows target is interesting to test because it enables
2824     // `-fdelayed-template-parsing`.
2825     config.Target = "x86_64-pc-win32-msvc";
2826     all_configs.push_back(config);
2827   }
2828   return all_configs;
2829 }
2830 
2831 INSTANTIATE_TEST_SUITE_P(
2832     ASTMatchersTests, ASTMatchersTest, testing::ValuesIn(allTestClangConfigs()),
2833     [](const testing::TestParamInfo<TestClangConfig> &Info) {
2834       return Info.param.toShortString();
2835     });
2836 
2837 } // namespace ast_matchers
2838 } // namespace clang
2839