1 // unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp - AST matcher unit tests//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ASTMatchersTest.h"
10 #include "clang/AST/PrettyPrinter.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Tooling/Tooling.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Support/Host.h"
16 #include "gtest/gtest.h"
17 
18 namespace clang {
19 namespace ast_matchers {
20 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_MatchesInFile)21 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesInFile) {
22   StringRef input = R"cc(
23 #define MY_MACRO(a) (4 + (a))
24     void Test() { MY_MACRO(4); }
25   )cc";
26   EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("MY_MACRO"))));
27 }
28 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_MatchesNested)29 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesNested) {
30   StringRef input = R"cc(
31 #define MY_MACRO(a) (4 + (a))
32 #define WRAPPER(a) MY_MACRO(a)
33     void Test() { WRAPPER(4); }
34   )cc";
35   EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("MY_MACRO"))));
36 }
37 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_MatchesIntermediate)38 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesIntermediate) {
39   StringRef input = R"cc(
40 #define IMPL(a) (4 + (a))
41 #define MY_MACRO(a) IMPL(a)
42 #define WRAPPER(a) MY_MACRO(a)
43     void Test() { WRAPPER(4); }
44   )cc";
45   EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("MY_MACRO"))));
46 }
47 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_MatchesTransitive)48 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesTransitive) {
49   StringRef input = R"cc(
50 #define MY_MACRO(a) (4 + (a))
51 #define WRAPPER(a) MY_MACRO(a)
52     void Test() { WRAPPER(4); }
53   )cc";
54   EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("WRAPPER"))));
55 }
56 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_MatchesArgument)57 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesArgument) {
58   StringRef input = R"cc(
59 #define MY_MACRO(a) (4 + (a))
60     void Test() {
61       int x = 5;
62       MY_MACRO(x);
63     }
64   )cc";
65   EXPECT_TRUE(matches(input, declRefExpr(isExpandedFromMacro("MY_MACRO"))));
66 }
67 
68 // Like IsExpandedFromMacro_MatchesArgument, but the argument is itself a
69 // macro.
TEST_P(ASTMatchersTest,IsExpandedFromMacro_MatchesArgumentMacroExpansion)70 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesArgumentMacroExpansion) {
71   StringRef input = R"cc(
72 #define MY_MACRO(a) (4 + (a))
73 #define IDENTITY(a) (a)
74     void Test() {
75       IDENTITY(MY_MACRO(2));
76     }
77   )cc";
78   EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("IDENTITY"))));
79 }
80 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_MatchesWhenInArgument)81 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesWhenInArgument) {
82   StringRef input = R"cc(
83 #define MY_MACRO(a) (4 + (a))
84 #define IDENTITY(a) (a)
85     void Test() {
86       IDENTITY(MY_MACRO(2));
87     }
88   )cc";
89   EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("MY_MACRO"))));
90 }
91 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_MatchesObjectMacro)92 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesObjectMacro) {
93   StringRef input = R"cc(
94 #define PLUS (2 + 2)
95     void Test() {
96       PLUS;
97     }
98   )cc";
99   EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("PLUS"))));
100 }
101 
TEST(IsExpandedFromMacro,MatchesFromCommandLine)102 TEST(IsExpandedFromMacro, MatchesFromCommandLine) {
103   StringRef input = R"cc(
104     void Test() { FOUR_PLUS_FOUR; }
105   )cc";
106   EXPECT_TRUE(matchesConditionally(
107       input, binaryOperator(isExpandedFromMacro("FOUR_PLUS_FOUR")), true,
108       {"-std=c++11", "-DFOUR_PLUS_FOUR=4+4"}));
109 }
110 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_NotMatchesBeginOnly)111 TEST_P(ASTMatchersTest, IsExpandedFromMacro_NotMatchesBeginOnly) {
112   StringRef input = R"cc(
113 #define ONE_PLUS 1+
114   void Test() { ONE_PLUS 4; }
115   )cc";
116   EXPECT_TRUE(
117       notMatches(input, binaryOperator(isExpandedFromMacro("ONE_PLUS"))));
118 }
119 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_NotMatchesEndOnly)120 TEST_P(ASTMatchersTest, IsExpandedFromMacro_NotMatchesEndOnly) {
121   StringRef input = R"cc(
122 #define PLUS_ONE +1
123   void Test() { 4 PLUS_ONE; }
124   )cc";
125   EXPECT_TRUE(
126       notMatches(input, binaryOperator(isExpandedFromMacro("PLUS_ONE"))));
127 }
128 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_NotMatchesDifferentMacro)129 TEST_P(ASTMatchersTest, IsExpandedFromMacro_NotMatchesDifferentMacro) {
130   StringRef input = R"cc(
131 #define MY_MACRO(a) (4 + (a))
132     void Test() { MY_MACRO(4); }
133   )cc";
134   EXPECT_TRUE(notMatches(input, binaryOperator(isExpandedFromMacro("OTHER"))));
135 }
136 
TEST_P(ASTMatchersTest,IsExpandedFromMacro_NotMatchesDifferentInstances)137 TEST_P(ASTMatchersTest, IsExpandedFromMacro_NotMatchesDifferentInstances) {
138   StringRef input = R"cc(
139 #define FOUR 4
140     void Test() { FOUR + FOUR; }
141   )cc";
142   EXPECT_TRUE(notMatches(input, binaryOperator(isExpandedFromMacro("FOUR"))));
143 }
144 
TEST(IsExpandedFromMacro,IsExpandedFromMacro_MatchesDecls)145 TEST(IsExpandedFromMacro, IsExpandedFromMacro_MatchesDecls) {
146   StringRef input = R"cc(
147 #define MY_MACRO(a) int i = a;
148     void Test() { MY_MACRO(4); }
149   )cc";
150   EXPECT_TRUE(matches(input, varDecl(isExpandedFromMacro("MY_MACRO"))));
151 }
152 
TEST(IsExpandedFromMacro,IsExpandedFromMacro_MatchesTypelocs)153 TEST(IsExpandedFromMacro, IsExpandedFromMacro_MatchesTypelocs) {
154   StringRef input = R"cc(
155 #define MY_TYPE int
156     void Test() { MY_TYPE i = 4; }
157   )cc";
158   EXPECT_TRUE(matches(input, typeLoc(isExpandedFromMacro("MY_TYPE"))));
159 }
160 
TEST_P(ASTMatchersTest,AllOf)161 TEST_P(ASTMatchersTest, AllOf) {
162   const char Program[] = "struct T { };"
163                          "int f(int, struct T*, int, int);"
164                          "void g(int x) { struct T t; f(x, &t, 3, 4); }";
165   EXPECT_TRUE(matches(
166       Program, callExpr(allOf(callee(functionDecl(hasName("f"))),
167                               hasArgument(0, declRefExpr(to(varDecl())))))));
168   EXPECT_TRUE(matches(
169       Program,
170       callExpr(
171           allOf(callee(functionDecl(hasName("f"))),
172                 hasArgument(0, declRefExpr(to(varDecl()))),
173                 hasArgument(1, hasType(pointsTo(recordDecl(hasName("T")))))))));
174   EXPECT_TRUE(matches(
175       Program, callExpr(allOf(
176                    callee(functionDecl(hasName("f"))),
177                    hasArgument(0, declRefExpr(to(varDecl()))),
178                    hasArgument(1, hasType(pointsTo(recordDecl(hasName("T"))))),
179                    hasArgument(2, integerLiteral(equals(3)))))));
180   EXPECT_TRUE(matches(
181       Program, callExpr(allOf(
182                    callee(functionDecl(hasName("f"))),
183                    hasArgument(0, declRefExpr(to(varDecl()))),
184                    hasArgument(1, hasType(pointsTo(recordDecl(hasName("T"))))),
185                    hasArgument(2, integerLiteral(equals(3))),
186                    hasArgument(3, integerLiteral(equals(4)))))));
187 }
188 
TEST_P(ASTMatchersTest,Has)189 TEST_P(ASTMatchersTest, Has) {
190   if (!GetParam().isCXX()) {
191     // FIXME: Add a test for `has()` that does not depend on C++.
192     return;
193   }
194 
195   DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
196   EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
197   EXPECT_TRUE(matches("class X {};", HasClassX));
198 
199   DeclarationMatcher YHasClassX =
200       recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
201   EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
202   EXPECT_TRUE(notMatches("class X {};", YHasClassX));
203   EXPECT_TRUE(notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
204 }
205 
TEST_P(ASTMatchersTest,Has_RecursiveAllOf)206 TEST_P(ASTMatchersTest, Has_RecursiveAllOf) {
207   if (!GetParam().isCXX()) {
208     return;
209   }
210 
211   DeclarationMatcher Recursive =
212       recordDecl(has(recordDecl(has(recordDecl(hasName("X"))),
213                                 has(recordDecl(hasName("Y"))), hasName("Z"))),
214                  has(recordDecl(has(recordDecl(hasName("A"))),
215                                 has(recordDecl(hasName("B"))), hasName("C"))),
216                  hasName("F"));
217 
218   EXPECT_TRUE(matches("class F {"
219                       "  class Z {"
220                       "    class X {};"
221                       "    class Y {};"
222                       "  };"
223                       "  class C {"
224                       "    class A {};"
225                       "    class B {};"
226                       "  };"
227                       "};",
228                       Recursive));
229 
230   EXPECT_TRUE(matches("class F {"
231                       "  class Z {"
232                       "    class A {};"
233                       "    class X {};"
234                       "    class Y {};"
235                       "  };"
236                       "  class C {"
237                       "    class X {};"
238                       "    class A {};"
239                       "    class B {};"
240                       "  };"
241                       "};",
242                       Recursive));
243 
244   EXPECT_TRUE(matches("class O1 {"
245                       "  class O2 {"
246                       "    class F {"
247                       "      class Z {"
248                       "        class A {};"
249                       "        class X {};"
250                       "        class Y {};"
251                       "      };"
252                       "      class C {"
253                       "        class X {};"
254                       "        class A {};"
255                       "        class B {};"
256                       "      };"
257                       "    };"
258                       "  };"
259                       "};",
260                       Recursive));
261 }
262 
TEST_P(ASTMatchersTest,Has_RecursiveAnyOf)263 TEST_P(ASTMatchersTest, Has_RecursiveAnyOf) {
264   if (!GetParam().isCXX()) {
265     return;
266   }
267 
268   DeclarationMatcher Recursive = recordDecl(
269       anyOf(has(recordDecl(anyOf(has(recordDecl(hasName("X"))),
270                                  has(recordDecl(hasName("Y"))), hasName("Z")))),
271             has(recordDecl(anyOf(hasName("C"), has(recordDecl(hasName("A"))),
272                                  has(recordDecl(hasName("B")))))),
273             hasName("F")));
274 
275   EXPECT_TRUE(matches("class F {};", Recursive));
276   EXPECT_TRUE(matches("class Z {};", Recursive));
277   EXPECT_TRUE(matches("class C {};", Recursive));
278   EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
279   EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
280   EXPECT_TRUE(matches("class O1 { class O2 {"
281                       "  class M { class N { class B {}; }; }; "
282                       "}; };",
283                       Recursive));
284 }
285 
TEST_P(ASTMatchersTest,Unless)286 TEST_P(ASTMatchersTest, Unless) {
287   if (!GetParam().isCXX()) {
288     // FIXME: Add a test for `unless()` that does not depend on C++.
289     return;
290   }
291 
292   DeclarationMatcher NotClassX =
293       cxxRecordDecl(isDerivedFrom("Y"), unless(hasName("X")));
294   EXPECT_TRUE(notMatches("", NotClassX));
295   EXPECT_TRUE(notMatches("class Y {};", NotClassX));
296   EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
297   EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
298   EXPECT_TRUE(
299       notMatches("class Y {}; class Z {}; class X : public Y {};", NotClassX));
300 
301   DeclarationMatcher ClassXHasNotClassY =
302       recordDecl(hasName("X"), has(recordDecl(hasName("Z"))),
303                  unless(has(recordDecl(hasName("Y")))));
304   EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
305   EXPECT_TRUE(
306       notMatches("class X { class Y {}; class Z {}; };", ClassXHasNotClassY));
307 
308   DeclarationMatcher NamedNotRecord =
309       namedDecl(hasName("Foo"), unless(recordDecl()));
310   EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
311   EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
312 }
313 
TEST_P(ASTMatchersTest,HasCastKind)314 TEST_P(ASTMatchersTest, HasCastKind) {
315   EXPECT_TRUE(
316       matches("char *p = 0;",
317               traverse(TK_AsIs,
318                        varDecl(has(castExpr(hasCastKind(CK_NullToPointer)))))));
319   EXPECT_TRUE(notMatches(
320       "char *p = 0;",
321       traverse(TK_AsIs,
322                varDecl(has(castExpr(hasCastKind(CK_DerivedToBase)))))));
323   EXPECT_TRUE(matches("char *p = 0;",
324                       traverse(TK_AsIs, varDecl(has(implicitCastExpr(
325                                             hasCastKind(CK_NullToPointer)))))));
326 }
327 
TEST_P(ASTMatchersTest,HasDescendant)328 TEST_P(ASTMatchersTest, HasDescendant) {
329   if (!GetParam().isCXX()) {
330     // FIXME: Add a test for `hasDescendant()` that does not depend on C++.
331     return;
332   }
333 
334   DeclarationMatcher ZDescendantClassX =
335       recordDecl(hasDescendant(recordDecl(hasName("X"))), hasName("Z"));
336   EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
337   EXPECT_TRUE(
338       matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
339   EXPECT_TRUE(matches("class Z { class A { class Y { class X {}; }; }; };",
340                       ZDescendantClassX));
341   EXPECT_TRUE(
342       matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
343               ZDescendantClassX));
344   EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
345 
346   DeclarationMatcher ZDescendantClassXHasClassY = recordDecl(
347       hasDescendant(recordDecl(has(recordDecl(hasName("Y"))), hasName("X"))),
348       hasName("Z"));
349   EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
350                       ZDescendantClassXHasClassY));
351   EXPECT_TRUE(
352       matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
353               ZDescendantClassXHasClassY));
354   EXPECT_TRUE(notMatches("class Z {"
355                          "  class A {"
356                          "    class B {"
357                          "      class X {"
358                          "        class C {"
359                          "          class Y {};"
360                          "        };"
361                          "      };"
362                          "    }; "
363                          "  };"
364                          "};",
365                          ZDescendantClassXHasClassY));
366 
367   DeclarationMatcher ZDescendantClassXDescendantClassY =
368       recordDecl(hasDescendant(recordDecl(
369                      hasDescendant(recordDecl(hasName("Y"))), hasName("X"))),
370                  hasName("Z"));
371   EXPECT_TRUE(
372       matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
373               ZDescendantClassXDescendantClassY));
374   EXPECT_TRUE(matches("class Z {"
375                       "  class A {"
376                       "    class X {"
377                       "      class B {"
378                       "        class Y {};"
379                       "      };"
380                       "      class Y {};"
381                       "    };"
382                       "  };"
383                       "};",
384                       ZDescendantClassXDescendantClassY));
385 }
386 
TEST_P(ASTMatchersTest,HasDescendant_Memoization)387 TEST_P(ASTMatchersTest, HasDescendant_Memoization) {
388   DeclarationMatcher CannotMemoize =
389       decl(hasDescendant(typeLoc().bind("x")), has(decl()));
390   EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
391 }
392 
TEST_P(ASTMatchersTest,HasDescendant_MemoizationUsesRestrictKind)393 TEST_P(ASTMatchersTest, HasDescendant_MemoizationUsesRestrictKind) {
394   auto Name = hasName("i");
395   auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
396   auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
397   // Matching VD first should not make a cache hit for RD.
398   EXPECT_TRUE(notMatches("void f() { int i; }",
399                          decl(hasDescendant(VD), hasDescendant(RD))));
400   EXPECT_TRUE(notMatches("void f() { int i; }",
401                          decl(hasDescendant(RD), hasDescendant(VD))));
402   // Not matching RD first should not make a cache hit for VD either.
403   EXPECT_TRUE(matches("void f() { int i; }",
404                       decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
405 }
406 
TEST_P(ASTMatchersTest,HasAncestor_Memoization)407 TEST_P(ASTMatchersTest, HasAncestor_Memoization) {
408   if (!GetParam().isCXX()) {
409     return;
410   }
411 
412   // This triggers an hasAncestor with a TemplateArgument in the bound nodes.
413   // That node can't be memoized so we have to check for it before trying to put
414   // it on the cache.
415   DeclarationMatcher CannotMemoize = classTemplateSpecializationDecl(
416       hasAnyTemplateArgument(templateArgument().bind("targ")),
417       forEach(fieldDecl(hasAncestor(forStmt()))));
418 
419   EXPECT_TRUE(notMatches("template <typename T> struct S;"
420                          "template <> struct S<int>{ int i; int j; };",
421                          CannotMemoize));
422 }
423 
TEST_P(ASTMatchersTest,HasAttr)424 TEST_P(ASTMatchersTest, HasAttr) {
425   EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
426                       decl(hasAttr(clang::attr::WarnUnused))));
427   EXPECT_FALSE(matches("struct X {};", decl(hasAttr(clang::attr::WarnUnused))));
428 }
429 
TEST_P(ASTMatchersTest,AnyOf)430 TEST_P(ASTMatchersTest, AnyOf) {
431   if (!GetParam().isCXX()) {
432     // FIXME: Add a test for `anyOf()` that does not depend on C++.
433     return;
434   }
435 
436   DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
437       anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
438   EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
439   EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
440   EXPECT_TRUE(
441       notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
442   EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
443 
444   DeclarationMatcher XOrYOrZOrU =
445       recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
446   EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
447   EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
448 
449   DeclarationMatcher XOrYOrZOrUOrV = recordDecl(anyOf(
450       hasName("X"), hasName("Y"), hasName("Z"), hasName("U"), hasName("V")));
451   EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
452   EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
453   EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
454   EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
455   EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
456   EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
457 
458   StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
459   EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
460   EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
461   EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
462 
463   EXPECT_TRUE(
464       matches("void f() try { } catch (int) { } catch (...) { }",
465               cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
466 }
467 
TEST_P(ASTMatchersTest,MapAnyOf)468 TEST_P(ASTMatchersTest, MapAnyOf) {
469   if (!GetParam().isCXX()) {
470     return;
471   }
472 
473   if (GetParam().hasDelayedTemplateParsing()) {
474     return;
475   }
476 
477   StringRef Code = R"cpp(
478 void F() {
479   if (true) {}
480   for ( ; false; ) {}
481 }
482 )cpp";
483 
484   auto trueExpr = cxxBoolLiteral(equals(true));
485   auto falseExpr = cxxBoolLiteral(equals(false));
486 
487   EXPECT_TRUE(matches(
488       Code, traverse(TK_IgnoreUnlessSpelledInSource,
489                      mapAnyOf(ifStmt, forStmt).with(hasCondition(trueExpr)))));
490   EXPECT_TRUE(matches(
491       Code, traverse(TK_IgnoreUnlessSpelledInSource,
492                      mapAnyOf(ifStmt, forStmt).with(hasCondition(falseExpr)))));
493 
494   EXPECT_TRUE(
495       matches(Code, cxxBoolLiteral(equals(true),
496                                    hasAncestor(mapAnyOf(ifStmt, forStmt)))));
497 
498   EXPECT_TRUE(
499       matches(Code, cxxBoolLiteral(equals(false),
500                                    hasAncestor(mapAnyOf(ifStmt, forStmt)))));
501 
502   EXPECT_TRUE(
503       notMatches(Code, floatLiteral(hasAncestor(mapAnyOf(ifStmt, forStmt)))));
504 
505   Code = R"cpp(
506 void func(bool b) {}
507 struct S {
508   S(bool b) {}
509 };
510 void F() {
511   func(false);
512   S s(true);
513 }
514 )cpp";
515   EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
516                                      mapAnyOf(callExpr, cxxConstructExpr)
517                                          .with(hasArgument(0, trueExpr)))));
518   EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
519                                      mapAnyOf(callExpr, cxxConstructExpr)
520                                          .with(hasArgument(0, falseExpr)))));
521 
522   EXPECT_TRUE(
523       matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
524                              mapAnyOf(callExpr, cxxConstructExpr)
525                                  .with(hasArgument(0, expr()),
526                                        hasDeclaration(functionDecl())))));
527 
528   EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
529                                      mapAnyOf(callExpr, cxxConstructExpr))));
530 
531   EXPECT_TRUE(matches(
532       Code, traverse(TK_IgnoreUnlessSpelledInSource,
533                      mapAnyOf(callExpr, cxxConstructExpr).bind("call"))));
534 
535   Code = R"cpp(
536 struct HasOpNeqMem
537 {
538     bool operator!=(const HasOpNeqMem& other) const
539     {
540         return true;
541     }
542 };
543 struct HasOpFree
544 {
545 };
546 bool operator!=(const HasOpFree& lhs, const HasOpFree& rhs)
547 {
548     return true;
549 }
550 
551 void binop()
552 {
553     int s1;
554     int s2;
555     if (s1 != s2)
556         return;
557 }
558 
559 void opMem()
560 {
561     HasOpNeqMem s1;
562     HasOpNeqMem s2;
563     if (s1 != s2)
564         return;
565 }
566 
567 void opFree()
568 {
569     HasOpFree s1;
570     HasOpFree s2;
571     if (s1 != s2)
572         return;
573 }
574 
575 template<typename T>
576 void templ()
577 {
578     T s1;
579     T s2;
580     if (s1 != s2)
581         return;
582 }
583 )cpp";
584 
585   EXPECT_TRUE(matches(
586       Code,
587       traverse(TK_IgnoreUnlessSpelledInSource,
588                mapAnyOf(binaryOperator, cxxOperatorCallExpr)
589                    .with(hasOperatorName("!="),
590                          forFunction(functionDecl(hasName("binop"))),
591                          hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
592                          hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
593 
594   EXPECT_TRUE(matches(
595       Code,
596       traverse(TK_IgnoreUnlessSpelledInSource,
597                mapAnyOf(binaryOperator, cxxOperatorCallExpr)
598                    .with(hasOperatorName("!="),
599                          forFunction(functionDecl(hasName("opMem"))),
600                          hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
601                          hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
602 
603   EXPECT_TRUE(matches(
604       Code,
605       traverse(TK_IgnoreUnlessSpelledInSource,
606                mapAnyOf(binaryOperator, cxxOperatorCallExpr)
607                    .with(hasOperatorName("!="),
608                          forFunction(functionDecl(hasName("opFree"))),
609                          hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
610                          hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
611 
612   EXPECT_TRUE(matches(
613       Code, traverse(TK_IgnoreUnlessSpelledInSource,
614                      mapAnyOf(binaryOperator, cxxOperatorCallExpr)
615                          .with(hasOperatorName("!="),
616                                forFunction(functionDecl(hasName("binop"))),
617                                hasEitherOperand(
618                                    declRefExpr(to(varDecl(hasName("s1"))))),
619                                hasEitherOperand(
620                                    declRefExpr(to(varDecl(hasName("s2")))))))));
621 
622   EXPECT_TRUE(matches(
623       Code, traverse(TK_IgnoreUnlessSpelledInSource,
624                      mapAnyOf(binaryOperator, cxxOperatorCallExpr)
625                          .with(hasOperatorName("!="),
626                                forFunction(functionDecl(hasName("opMem"))),
627                                hasEitherOperand(
628                                    declRefExpr(to(varDecl(hasName("s1"))))),
629                                hasEitherOperand(
630                                    declRefExpr(to(varDecl(hasName("s2")))))))));
631 
632   EXPECT_TRUE(matches(
633       Code, traverse(TK_IgnoreUnlessSpelledInSource,
634                      mapAnyOf(binaryOperator, cxxOperatorCallExpr)
635                          .with(hasOperatorName("!="),
636                                forFunction(functionDecl(hasName("opFree"))),
637                                hasEitherOperand(
638                                    declRefExpr(to(varDecl(hasName("s1"))))),
639                                hasEitherOperand(
640                                    declRefExpr(to(varDecl(hasName("s2")))))))));
641 
642   EXPECT_TRUE(matches(
643       Code,
644       traverse(
645           TK_IgnoreUnlessSpelledInSource,
646           mapAnyOf(binaryOperator, cxxOperatorCallExpr)
647               .with(hasOperatorName("!="),
648                     forFunction(functionDecl(hasName("binop"))),
649                     hasOperands(declRefExpr(to(varDecl(hasName("s1")))),
650                                 declRefExpr(to(varDecl(hasName("s2"))))),
651                     hasOperands(declRefExpr(to(varDecl(hasName("s2")))),
652                                 declRefExpr(to(varDecl(hasName("s1")))))))));
653 
654   EXPECT_TRUE(matches(
655       Code,
656       traverse(
657           TK_IgnoreUnlessSpelledInSource,
658           mapAnyOf(binaryOperator, cxxOperatorCallExpr)
659               .with(hasOperatorName("!="),
660                     forFunction(functionDecl(hasName("opMem"))),
661                     hasOperands(declRefExpr(to(varDecl(hasName("s1")))),
662                                 declRefExpr(to(varDecl(hasName("s2"))))),
663                     hasOperands(declRefExpr(to(varDecl(hasName("s2")))),
664                                 declRefExpr(to(varDecl(hasName("s1")))))))));
665 
666   EXPECT_TRUE(matches(
667       Code,
668       traverse(
669           TK_IgnoreUnlessSpelledInSource,
670           mapAnyOf(binaryOperator, cxxOperatorCallExpr)
671               .with(hasOperatorName("!="),
672                     forFunction(functionDecl(hasName("opFree"))),
673                     hasOperands(declRefExpr(to(varDecl(hasName("s1")))),
674                                 declRefExpr(to(varDecl(hasName("s2"))))),
675                     hasOperands(declRefExpr(to(varDecl(hasName("s2")))),
676                                 declRefExpr(to(varDecl(hasName("s1")))))))));
677 
678   EXPECT_TRUE(matches(
679       Code, traverse(TK_IgnoreUnlessSpelledInSource,
680                      mapAnyOf(binaryOperator, cxxOperatorCallExpr)
681                          .with(hasAnyOperatorName("==", "!="),
682                                forFunction(functionDecl(hasName("binop")))))));
683 
684   EXPECT_TRUE(matches(
685       Code, traverse(TK_IgnoreUnlessSpelledInSource,
686                      mapAnyOf(binaryOperator, cxxOperatorCallExpr)
687                          .with(hasAnyOperatorName("==", "!="),
688                                forFunction(functionDecl(hasName("opMem")))))));
689 
690   EXPECT_TRUE(matches(
691       Code, traverse(TK_IgnoreUnlessSpelledInSource,
692                      mapAnyOf(binaryOperator, cxxOperatorCallExpr)
693                          .with(hasAnyOperatorName("==", "!="),
694                                forFunction(functionDecl(hasName("opFree")))))));
695 
696   EXPECT_TRUE(matches(
697       Code, traverse(TK_IgnoreUnlessSpelledInSource,
698                      binaryOperation(
699                          hasOperatorName("!="),
700                          forFunction(functionDecl(hasName("binop"))),
701                          hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
702                          hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
703 
704   EXPECT_TRUE(matches(
705       Code, traverse(TK_IgnoreUnlessSpelledInSource,
706                      binaryOperation(
707                          hasOperatorName("!="),
708                          forFunction(functionDecl(hasName("opMem"))),
709                          hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
710                          hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
711 
712   EXPECT_TRUE(matches(
713       Code, traverse(TK_IgnoreUnlessSpelledInSource,
714                      binaryOperation(
715                          hasOperatorName("!="),
716                          forFunction(functionDecl(hasName("opFree"))),
717                          hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
718                          hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
719 
720   EXPECT_TRUE(matches(
721       Code, traverse(TK_IgnoreUnlessSpelledInSource,
722                      binaryOperation(
723                          hasOperatorName("!="),
724                          forFunction(functionDecl(hasName("templ"))),
725                          hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
726                          hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
727 
728   Code = R"cpp(
729 struct HasOpEq
730 {
731     bool operator==(const HasOpEq &) const;
732 };
733 
734 void inverse()
735 {
736     HasOpEq s1;
737     HasOpEq s2;
738     if (s1 != s2)
739         return;
740 }
741 
742 namespace std {
743 struct strong_ordering {
744   int n;
745   constexpr operator int() const { return n; }
746   static const strong_ordering equal, greater, less;
747 };
748 constexpr strong_ordering strong_ordering::equal = {0};
749 constexpr strong_ordering strong_ordering::greater = {1};
750 constexpr strong_ordering strong_ordering::less = {-1};
751 }
752 
753 struct HasSpaceshipMem {
754   int a;
755   constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
756 };
757 
758 void rewritten()
759 {
760     HasSpaceshipMem s1;
761     HasSpaceshipMem s2;
762     if (s1 != s2)
763         return;
764 }
765 )cpp";
766 
767   EXPECT_TRUE(matchesConditionally(
768       Code,
769       traverse(
770           TK_IgnoreUnlessSpelledInSource,
771           binaryOperation(hasOperatorName("!="),
772                           forFunction(functionDecl(hasName("inverse"))),
773                           hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
774                           hasRHS(declRefExpr(to(varDecl(hasName("s2"))))))),
775       true, {"-std=c++20"}));
776 
777   EXPECT_TRUE(matchesConditionally(
778       Code,
779       traverse(
780           TK_IgnoreUnlessSpelledInSource,
781           binaryOperation(hasOperatorName("!="),
782                           forFunction(functionDecl(hasName("rewritten"))),
783                           hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
784                           hasRHS(declRefExpr(to(varDecl(hasName("s2"))))))),
785       true, {"-std=c++20"}));
786 
787   Code = R"cpp(
788 struct HasOpBangMem
789 {
790     bool operator!() const
791     {
792         return false;
793     }
794 };
795 struct HasOpBangFree
796 {
797 };
798 bool operator!(HasOpBangFree const&)
799 {
800     return false;
801 }
802 
803 void unop()
804 {
805     int s1;
806     if (!s1)
807         return;
808 }
809 
810 void opMem()
811 {
812     HasOpBangMem s1;
813     if (!s1)
814         return;
815 }
816 
817 void opFree()
818 {
819     HasOpBangFree s1;
820     if (!s1)
821         return;
822 }
823 )cpp";
824 
825   EXPECT_TRUE(matches(
826       Code, traverse(TK_IgnoreUnlessSpelledInSource,
827                      mapAnyOf(unaryOperator, cxxOperatorCallExpr)
828                          .with(hasOperatorName("!"),
829                                forFunction(functionDecl(hasName("unop"))),
830                                hasUnaryOperand(
831                                    declRefExpr(to(varDecl(hasName("s1")))))))));
832 
833   EXPECT_TRUE(matches(
834       Code, traverse(TK_IgnoreUnlessSpelledInSource,
835                      mapAnyOf(unaryOperator, cxxOperatorCallExpr)
836                          .with(hasOperatorName("!"),
837                                forFunction(functionDecl(hasName("opMem"))),
838                                hasUnaryOperand(
839                                    declRefExpr(to(varDecl(hasName("s1")))))))));
840 
841   EXPECT_TRUE(matches(
842       Code, traverse(TK_IgnoreUnlessSpelledInSource,
843                      mapAnyOf(unaryOperator, cxxOperatorCallExpr)
844                          .with(hasOperatorName("!"),
845                                forFunction(functionDecl(hasName("opFree"))),
846                                hasUnaryOperand(
847                                    declRefExpr(to(varDecl(hasName("s1")))))))));
848 
849   EXPECT_TRUE(matches(
850       Code, traverse(TK_IgnoreUnlessSpelledInSource,
851                      mapAnyOf(unaryOperator, cxxOperatorCallExpr)
852                          .with(hasAnyOperatorName("+", "!"),
853                                forFunction(functionDecl(hasName("unop")))))));
854 
855   EXPECT_TRUE(matches(
856       Code, traverse(TK_IgnoreUnlessSpelledInSource,
857                      mapAnyOf(unaryOperator, cxxOperatorCallExpr)
858                          .with(hasAnyOperatorName("+", "!"),
859                                forFunction(functionDecl(hasName("opMem")))))));
860 
861   EXPECT_TRUE(matches(
862       Code, traverse(TK_IgnoreUnlessSpelledInSource,
863                      mapAnyOf(unaryOperator, cxxOperatorCallExpr)
864                          .with(hasAnyOperatorName("+", "!"),
865                                forFunction(functionDecl(hasName("opFree")))))));
866 
867   Code = R"cpp(
868 struct ConstructorTakesInt
869 {
870   ConstructorTakesInt(int i) {}
871 };
872 
873 void callTakesInt(int i)
874 {
875 
876 }
877 
878 void doCall()
879 {
880   callTakesInt(42);
881 }
882 
883 void doConstruct()
884 {
885   ConstructorTakesInt cti(42);
886 }
887 )cpp";
888 
889   EXPECT_TRUE(matches(
890       Code, traverse(TK_IgnoreUnlessSpelledInSource,
891                      invocation(forFunction(functionDecl(hasName("doCall"))),
892                                 hasArgument(0, integerLiteral(equals(42))),
893                                 hasAnyArgument(integerLiteral(equals(42))),
894                                 forEachArgumentWithParam(
895                                     integerLiteral(equals(42)),
896                                     parmVarDecl(hasName("i")))))));
897 
898   EXPECT_TRUE(matches(
899       Code,
900       traverse(
901           TK_IgnoreUnlessSpelledInSource,
902           invocation(forFunction(functionDecl(hasName("doConstruct"))),
903                      hasArgument(0, integerLiteral(equals(42))),
904                      hasAnyArgument(integerLiteral(equals(42))),
905                      forEachArgumentWithParam(integerLiteral(equals(42)),
906                                               parmVarDecl(hasName("i")))))));
907 }
908 
TEST_P(ASTMatchersTest,IsDerivedFrom)909 TEST_P(ASTMatchersTest, IsDerivedFrom) {
910   if (!GetParam().isCXX()) {
911     return;
912   }
913 
914   DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
915 
916   EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
917   EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
918   EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
919   EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
920   EXPECT_TRUE(notMatches("", IsDerivedFromX));
921   EXPECT_TRUE(matches("class X {}; template<int N> class Y : Y<N-1>, X {};",
922                       IsDerivedFromX));
923   EXPECT_TRUE(matches("class X {}; template<int N> class Y : X, Y<N-1> {};",
924                       IsDerivedFromX));
925 
926   DeclarationMatcher IsZDerivedFromX =
927       cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
928   EXPECT_TRUE(matches("class X {};"
929                       "template<int N> class Y : Y<N-1> {};"
930                       "template<> class Y<0> : X {};"
931                       "class Z : Y<1> {};",
932                       IsZDerivedFromX));
933 
934   DeclarationMatcher IsDirectlyDerivedFromX =
935       cxxRecordDecl(isDirectlyDerivedFrom("X"));
936 
937   EXPECT_TRUE(
938       matches("class X {}; class Y : public X {};", IsDirectlyDerivedFromX));
939   EXPECT_TRUE(notMatches("class X {};", IsDirectlyDerivedFromX));
940   EXPECT_TRUE(notMatches("class X;", IsDirectlyDerivedFromX));
941   EXPECT_TRUE(notMatches("class Y;", IsDirectlyDerivedFromX));
942   EXPECT_TRUE(notMatches("", IsDirectlyDerivedFromX));
943 
944   DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
945 
946   EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
947   EXPECT_TRUE(matches("class X {};", IsAX));
948   EXPECT_TRUE(matches("class X;", IsAX));
949   EXPECT_TRUE(notMatches("class Y;", IsAX));
950   EXPECT_TRUE(notMatches("", IsAX));
951 
952   DeclarationMatcher ZIsDerivedFromX =
953       cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
954   DeclarationMatcher ZIsDirectlyDerivedFromX =
955       cxxRecordDecl(hasName("Z"), isDirectlyDerivedFrom("X"));
956   EXPECT_TRUE(
957       matches("class X {}; class Y : public X {}; class Z : public Y {};",
958               ZIsDerivedFromX));
959   EXPECT_TRUE(
960       notMatches("class X {}; class Y : public X {}; class Z : public Y {};",
961                  ZIsDirectlyDerivedFromX));
962   EXPECT_TRUE(matches("class X {};"
963                       "template<class T> class Y : public X {};"
964                       "class Z : public Y<int> {};",
965                       ZIsDerivedFromX));
966   EXPECT_TRUE(notMatches("class X {};"
967                          "template<class T> class Y : public X {};"
968                          "class Z : public Y<int> {};",
969                          ZIsDirectlyDerivedFromX));
970   EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
971                       ZIsDerivedFromX));
972   EXPECT_TRUE(matches("template<class T> class X {}; "
973                       "template<class T> class Z : public X<T> {};",
974                       ZIsDerivedFromX));
975   EXPECT_TRUE(matches("template<class T, class U=T> class X {}; "
976                       "template<class T> class Z : public X<T> {};",
977                       ZIsDerivedFromX));
978   EXPECT_TRUE(
979       notMatches("template<class X> class A { class Z : public X {}; };",
980                  ZIsDerivedFromX));
981   EXPECT_TRUE(
982       matches("template<class X> class A { public: class Z : public X {}; }; "
983               "class X{}; void y() { A<X>::Z z; }",
984               ZIsDerivedFromX));
985   EXPECT_TRUE(
986       matches("template <class T> class X {}; "
987               "template<class Y> class A { class Z : public X<Y> {}; };",
988               ZIsDerivedFromX));
989   EXPECT_TRUE(notMatches("template<template<class T> class X> class A { "
990                          "  class Z : public X<int> {}; };",
991                          ZIsDerivedFromX));
992   EXPECT_TRUE(matches("template<template<class T> class X> class A { "
993                       "  public: class Z : public X<int> {}; }; "
994                       "template<class T> class X {}; void y() { A<X>::Z z; }",
995                       ZIsDerivedFromX));
996   EXPECT_TRUE(
997       notMatches("template<class X> class A { class Z : public X::D {}; };",
998                  ZIsDerivedFromX));
999   EXPECT_TRUE(matches("template<class X> class A { public: "
1000                       "  class Z : public X::D {}; }; "
1001                       "class Y { public: class X {}; typedef X D; }; "
1002                       "void y() { A<Y>::Z z; }",
1003                       ZIsDerivedFromX));
1004   EXPECT_TRUE(matches("class X {}; typedef X Y; class Z : public Y {};",
1005                       ZIsDerivedFromX));
1006   EXPECT_TRUE(matches("template<class T> class Y { typedef typename T::U X; "
1007                       "  class Z : public X {}; };",
1008                       ZIsDerivedFromX));
1009   EXPECT_TRUE(matches("class X {}; class Z : public ::X {};", ZIsDerivedFromX));
1010   EXPECT_TRUE(
1011       notMatches("template<class T> class X {}; "
1012                  "template<class T> class A { class Z : public X<T>::D {}; };",
1013                  ZIsDerivedFromX));
1014   EXPECT_TRUE(
1015       matches("template<class T> class X { public: typedef X<T> D; }; "
1016               "template<class T> class A { public: "
1017               "  class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
1018               ZIsDerivedFromX));
1019   EXPECT_TRUE(
1020       notMatches("template<class X> class A { class Z : public X::D::E {}; };",
1021                  ZIsDerivedFromX));
1022   EXPECT_TRUE(
1023       matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
1024               ZIsDerivedFromX));
1025   EXPECT_TRUE(matches("class X {}; class Y : public X {}; "
1026                       "typedef Y V; typedef V W; class Z : public W {};",
1027                       ZIsDerivedFromX));
1028   EXPECT_TRUE(notMatches("class X {}; class Y : public X {}; "
1029                          "typedef Y V; typedef V W; class Z : public W {};",
1030                          ZIsDirectlyDerivedFromX));
1031   EXPECT_TRUE(
1032       matches("template<class T, class U> class X {}; "
1033               "template<class T> class A { class Z : public X<T, int> {}; };",
1034               ZIsDerivedFromX));
1035   EXPECT_TRUE(
1036       notMatches("template<class X> class D { typedef X A; typedef A B; "
1037                  "  typedef B C; class Z : public C {}; };",
1038                  ZIsDerivedFromX));
1039   EXPECT_TRUE(matches("class X {}; typedef X A; typedef A B; "
1040                       "class Z : public B {};",
1041                       ZIsDerivedFromX));
1042   EXPECT_TRUE(matches("class X {}; typedef X A; typedef A B; typedef B C; "
1043                       "class Z : public C {};",
1044                       ZIsDerivedFromX));
1045   EXPECT_TRUE(matches("class U {}; typedef U X; typedef X V; "
1046                       "class Z : public V {};",
1047                       ZIsDerivedFromX));
1048   EXPECT_TRUE(matches("class Base {}; typedef Base X; "
1049                       "class Z : public Base {};",
1050                       ZIsDerivedFromX));
1051   EXPECT_TRUE(matches("class Base {}; typedef Base Base2; typedef Base2 X; "
1052                       "class Z : public Base {};",
1053                       ZIsDerivedFromX));
1054   EXPECT_TRUE(notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
1055                          "class Z : public Base {};",
1056                          ZIsDerivedFromX));
1057   EXPECT_TRUE(matches("class A {}; typedef A X; typedef A Y; "
1058                       "class Z : public Y {};",
1059                       ZIsDerivedFromX));
1060   EXPECT_TRUE(notMatches("template <typename T> class Z;"
1061                          "template <> class Z<void> {};"
1062                          "template <typename T> class Z : public Z<void> {};",
1063                          IsDerivedFromX));
1064   EXPECT_TRUE(matches("template <typename T> class X;"
1065                       "template <> class X<void> {};"
1066                       "template <typename T> class X : public X<void> {};",
1067                       IsDerivedFromX));
1068   EXPECT_TRUE(
1069       matches("class X {};"
1070               "template <typename T> class Z;"
1071               "template <> class Z<void> {};"
1072               "template <typename T> class Z : public Z<void>, public X {};",
1073               ZIsDerivedFromX));
1074   EXPECT_TRUE(
1075       notMatches("template<int> struct X;"
1076                  "template<int i> struct X : public X<i-1> {};",
1077                  cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
1078   EXPECT_TRUE(matches(
1079       "struct A {};"
1080       "template<int> struct X;"
1081       "template<int i> struct X : public X<i-1> {};"
1082       "template<> struct X<0> : public A {};"
1083       "struct B : public X<42> {};",
1084       cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
1085   EXPECT_TRUE(notMatches(
1086       "struct A {};"
1087       "template<int> struct X;"
1088       "template<int i> struct X : public X<i-1> {};"
1089       "template<> struct X<0> : public A {};"
1090       "struct B : public X<42> {};",
1091       cxxRecordDecl(hasName("B"),
1092                     isDirectlyDerivedFrom(recordDecl(hasName("A"))))));
1093 
1094   // FIXME: Once we have better matchers for template type matching,
1095   // get rid of the Variable(...) matching and match the right template
1096   // declarations directly.
1097   const char *RecursiveTemplateOneParameter =
1098       "class Base1 {}; class Base2 {};"
1099       "template <typename T> class Z;"
1100       "template <> class Z<void> : public Base1 {};"
1101       "template <> class Z<int> : public Base2 {};"
1102       "template <> class Z<float> : public Z<void> {};"
1103       "template <> class Z<double> : public Z<int> {};"
1104       "template <typename T> class Z : public Z<float>, public Z<double> {};"
1105       "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
1106   EXPECT_TRUE(matches(
1107       RecursiveTemplateOneParameter,
1108       varDecl(hasName("z_float"),
1109               hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
1110   EXPECT_TRUE(notMatches(
1111       RecursiveTemplateOneParameter,
1112       varDecl(hasName("z_float"),
1113               hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
1114   EXPECT_TRUE(
1115       matches(RecursiveTemplateOneParameter,
1116               varDecl(hasName("z_char"),
1117                       hasInitializer(hasType(cxxRecordDecl(
1118                           isDerivedFrom("Base1"), isDerivedFrom("Base2")))))));
1119 
1120   const char *RecursiveTemplateTwoParameters =
1121       "class Base1 {}; class Base2 {};"
1122       "template <typename T1, typename T2> class Z;"
1123       "template <typename T> class Z<void, T> : public Base1 {};"
1124       "template <typename T> class Z<int, T> : public Base2 {};"
1125       "template <typename T> class Z<float, T> : public Z<void, T> {};"
1126       "template <typename T> class Z<double, T> : public Z<int, T> {};"
1127       "template <typename T1, typename T2> class Z : "
1128       "    public Z<float, T2>, public Z<double, T2> {};"
1129       "void f() { Z<float, void> z_float; Z<double, void> z_double; "
1130       "           Z<char, void> z_char; }";
1131   EXPECT_TRUE(matches(
1132       RecursiveTemplateTwoParameters,
1133       varDecl(hasName("z_float"),
1134               hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
1135   EXPECT_TRUE(notMatches(
1136       RecursiveTemplateTwoParameters,
1137       varDecl(hasName("z_float"),
1138               hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
1139   EXPECT_TRUE(
1140       matches(RecursiveTemplateTwoParameters,
1141               varDecl(hasName("z_char"),
1142                       hasInitializer(hasType(cxxRecordDecl(
1143                           isDerivedFrom("Base1"), isDerivedFrom("Base2")))))));
1144   EXPECT_TRUE(matches("namespace ns { class X {}; class Y : public X {}; }",
1145                       cxxRecordDecl(isDerivedFrom("::ns::X"))));
1146   EXPECT_TRUE(notMatches("class X {}; class Y : public X {};",
1147                          cxxRecordDecl(isDerivedFrom("::ns::X"))));
1148 
1149   EXPECT_TRUE(matches(
1150       "class X {}; class Y : public X {};",
1151       cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
1152 
1153   EXPECT_TRUE(matches("template<typename T> class X {};"
1154                       "template<typename T> using Z = X<T>;"
1155                       "template <typename T> class Y : Z<T> {};",
1156                       cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
1157 }
1158 
TEST_P(ASTMatchersTest,IsDerivedFrom_EmptyName)1159 TEST_P(ASTMatchersTest, IsDerivedFrom_EmptyName) {
1160   if (!GetParam().isCXX()) {
1161     return;
1162   }
1163 
1164   const char *const Code = "class X {}; class Y : public X {};";
1165   EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isDerivedFrom(""))));
1166   EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isDirectlyDerivedFrom(""))));
1167   EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isSameOrDerivedFrom(""))));
1168 }
1169 
TEST_P(ASTMatchersTest,IsDerivedFrom_ObjC)1170 TEST_P(ASTMatchersTest, IsDerivedFrom_ObjC) {
1171   DeclarationMatcher IsDerivedFromX = objcInterfaceDecl(isDerivedFrom("X"));
1172   EXPECT_TRUE(
1173       matchesObjC("@interface X @end @interface Y : X @end", IsDerivedFromX));
1174   EXPECT_TRUE(matchesObjC(
1175       "@interface X @end @interface Y<__covariant ObjectType> : X @end",
1176       IsDerivedFromX));
1177   EXPECT_TRUE(matchesObjC(
1178       "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
1179       IsDerivedFromX));
1180   EXPECT_TRUE(matchesObjC(
1181       "@interface X @end typedef X Y; @interface Z : Y @end", IsDerivedFromX));
1182   EXPECT_TRUE(notMatchesObjC("@interface X @end", IsDerivedFromX));
1183   EXPECT_TRUE(notMatchesObjC("@class X;", IsDerivedFromX));
1184   EXPECT_TRUE(notMatchesObjC("@class Y;", IsDerivedFromX));
1185   EXPECT_TRUE(notMatchesObjC("@interface X @end @compatibility_alias Y X;",
1186                              IsDerivedFromX));
1187   EXPECT_TRUE(notMatchesObjC("@interface X @end typedef X Y;", IsDerivedFromX));
1188 
1189   DeclarationMatcher IsDirectlyDerivedFromX =
1190       objcInterfaceDecl(isDirectlyDerivedFrom("X"));
1191   EXPECT_TRUE(matchesObjC("@interface X @end @interface Y : X @end",
1192                           IsDirectlyDerivedFromX));
1193   EXPECT_TRUE(matchesObjC(
1194       "@interface X @end @interface Y<__covariant ObjectType> : X @end",
1195       IsDirectlyDerivedFromX));
1196   EXPECT_TRUE(matchesObjC(
1197       "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
1198       IsDirectlyDerivedFromX));
1199   EXPECT_TRUE(
1200       matchesObjC("@interface X @end typedef X Y; @interface Z : Y @end",
1201                   IsDirectlyDerivedFromX));
1202   EXPECT_TRUE(notMatchesObjC("@interface X @end", IsDirectlyDerivedFromX));
1203   EXPECT_TRUE(notMatchesObjC("@class X;", IsDirectlyDerivedFromX));
1204   EXPECT_TRUE(notMatchesObjC("@class Y;", IsDirectlyDerivedFromX));
1205   EXPECT_TRUE(notMatchesObjC("@interface X @end @compatibility_alias Y X;",
1206                              IsDirectlyDerivedFromX));
1207   EXPECT_TRUE(
1208       notMatchesObjC("@interface X @end typedef X Y;", IsDirectlyDerivedFromX));
1209 
1210   DeclarationMatcher IsAX = objcInterfaceDecl(isSameOrDerivedFrom("X"));
1211   EXPECT_TRUE(matchesObjC("@interface X @end @interface Y : X @end", IsAX));
1212   EXPECT_TRUE(matchesObjC("@interface X @end", IsAX));
1213   EXPECT_TRUE(matchesObjC("@class X;", IsAX));
1214   EXPECT_TRUE(notMatchesObjC("@interface Y @end", IsAX));
1215   EXPECT_TRUE(notMatchesObjC("@class Y;", IsAX));
1216 
1217   DeclarationMatcher ZIsDerivedFromX =
1218       objcInterfaceDecl(hasName("Z"), isDerivedFrom("X"));
1219   DeclarationMatcher ZIsDirectlyDerivedFromX =
1220       objcInterfaceDecl(hasName("Z"), isDirectlyDerivedFrom("X"));
1221   EXPECT_TRUE(matchesObjC(
1222       "@interface X @end @interface Y : X @end @interface Z : Y @end",
1223       ZIsDerivedFromX));
1224   EXPECT_TRUE(matchesObjC("@interface X @end @interface Y : X @end typedef Y "
1225                           "V; typedef V W; @interface Z : W @end",
1226                           ZIsDerivedFromX));
1227   EXPECT_TRUE(matchesObjC(
1228       "@interface X @end typedef X Y; @interface Z : Y @end", ZIsDerivedFromX));
1229   EXPECT_TRUE(
1230       matchesObjC("@interface X @end typedef X Y; @interface Z : Y @end",
1231                   ZIsDirectlyDerivedFromX));
1232   EXPECT_TRUE(matchesObjC(
1233       "@interface A @end typedef A X; typedef A Y; @interface Z : Y @end",
1234       ZIsDerivedFromX));
1235   EXPECT_TRUE(matchesObjC(
1236       "@interface A @end typedef A X; typedef A Y; @interface Z : Y @end",
1237       ZIsDirectlyDerivedFromX));
1238   EXPECT_TRUE(matchesObjC(
1239       "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
1240       ZIsDerivedFromX));
1241   EXPECT_TRUE(matchesObjC(
1242       "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
1243       ZIsDirectlyDerivedFromX));
1244   EXPECT_TRUE(matchesObjC(
1245       "@interface Y @end @compatibility_alias X Y; @interface Z : Y @end",
1246       ZIsDerivedFromX));
1247   EXPECT_TRUE(matchesObjC(
1248       "@interface Y @end @compatibility_alias X Y; @interface Z : Y @end",
1249       ZIsDirectlyDerivedFromX));
1250   EXPECT_TRUE(matchesObjC(
1251       "@interface A @end @compatibility_alias X A; @compatibility_alias Y A;"
1252       "@interface Z : Y @end",
1253       ZIsDerivedFromX));
1254   EXPECT_TRUE(matchesObjC(
1255       "@interface A @end @compatibility_alias X A; @compatibility_alias Y A;"
1256       "@interface Z : Y @end",
1257       ZIsDirectlyDerivedFromX));
1258   EXPECT_TRUE(matchesObjC(
1259       "@interface Y @end typedef Y X; @interface Z : X @end", ZIsDerivedFromX));
1260   EXPECT_TRUE(
1261       matchesObjC("@interface Y @end typedef Y X; @interface Z : X @end",
1262                   ZIsDirectlyDerivedFromX));
1263   EXPECT_TRUE(
1264       matchesObjC("@interface A @end @compatibility_alias Y A; typedef Y X;"
1265                   "@interface Z : A @end",
1266                   ZIsDerivedFromX));
1267   EXPECT_TRUE(
1268       matchesObjC("@interface A @end @compatibility_alias Y A; typedef Y X;"
1269                   "@interface Z : A @end",
1270                   ZIsDirectlyDerivedFromX));
1271   EXPECT_TRUE(
1272       matchesObjC("@interface A @end typedef A Y; @compatibility_alias X Y;"
1273                   "@interface Z : A @end",
1274                   ZIsDerivedFromX));
1275   EXPECT_TRUE(
1276       matchesObjC("@interface A @end typedef A Y; @compatibility_alias X Y;"
1277                   "@interface Z : A @end",
1278                   ZIsDirectlyDerivedFromX));
1279 }
1280 
TEST_P(ASTMatchersTest,IsLambda)1281 TEST_P(ASTMatchersTest, IsLambda) {
1282   if (!GetParam().isCXX11OrLater()) {
1283     return;
1284   }
1285 
1286   const auto IsLambda = cxxMethodDecl(ofClass(cxxRecordDecl(isLambda())));
1287   EXPECT_TRUE(matches("auto x = []{};", IsLambda));
1288   EXPECT_TRUE(notMatches("struct S { void operator()() const; };", IsLambda));
1289 }
1290 
TEST_P(ASTMatchersTest,Bind)1291 TEST_P(ASTMatchersTest, Bind) {
1292   DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
1293 
1294   EXPECT_TRUE(matchAndVerifyResultTrue(
1295       "class X {};", ClassX,
1296       std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x")));
1297 
1298   EXPECT_TRUE(matchAndVerifyResultFalse(
1299       "class X {};", ClassX,
1300       std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("other-id")));
1301 
1302   TypeMatcher TypeAHasClassB = hasDeclaration(
1303       recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
1304 
1305   EXPECT_TRUE(matchAndVerifyResultTrue(
1306       "class A { public: A *a; class B {}; };", TypeAHasClassB,
1307       std::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
1308 
1309   StatementMatcher MethodX =
1310       callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
1311 
1312   EXPECT_TRUE(matchAndVerifyResultTrue(
1313       "class A { void x() { x(); } };", MethodX,
1314       std::make_unique<VerifyIdIsBoundTo<CXXMemberCallExpr>>("x")));
1315 }
1316 
TEST_P(ASTMatchersTest,Bind_SameNameInAlternatives)1317 TEST_P(ASTMatchersTest, Bind_SameNameInAlternatives) {
1318   StatementMatcher matcher = anyOf(
1319       binaryOperator(hasOperatorName("+"), hasLHS(expr().bind("x")),
1320                      hasRHS(integerLiteral(equals(0)))),
1321       binaryOperator(hasOperatorName("+"), hasLHS(integerLiteral(equals(0))),
1322                      hasRHS(expr().bind("x"))));
1323 
1324   EXPECT_TRUE(matchAndVerifyResultTrue(
1325       // The first branch of the matcher binds x to 0 but then fails.
1326       // The second branch binds x to f() and succeeds.
1327       "int f() { return 0 + f(); }", matcher,
1328       std::make_unique<VerifyIdIsBoundTo<CallExpr>>("x")));
1329 }
1330 
TEST_P(ASTMatchersTest,Bind_BindsIDForMemoizedResults)1331 TEST_P(ASTMatchersTest, Bind_BindsIDForMemoizedResults) {
1332   // Using the same matcher in two match expressions will make memoization
1333   // kick in.
1334   DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
1335   EXPECT_TRUE(matchAndVerifyResultTrue(
1336       "class A { class B { class X {}; }; };",
1337       DeclarationMatcher(
1338           anyOf(recordDecl(hasName("A"), hasDescendant(ClassX)),
1339                 recordDecl(hasName("B"), hasDescendant(ClassX)))),
1340       std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 2)));
1341 }
1342 
TEST_P(ASTMatchersTest,HasType_MatchesAsString)1343 TEST_P(ASTMatchersTest, HasType_MatchesAsString) {
1344   if (!GetParam().isCXX()) {
1345     // FIXME: Add a test for `hasType()` that does not depend on C++.
1346     return;
1347   }
1348 
1349   EXPECT_TRUE(
1350       matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
1351               cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
1352   EXPECT_TRUE(
1353       matches("class X { void x(int x) {} };",
1354               cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
1355   EXPECT_TRUE(matches("namespace ns { struct A {}; }  struct B { ns::A a; };",
1356                       fieldDecl(hasType(asString("ns::A")))));
1357   EXPECT_TRUE(
1358       matches("namespace { struct A {}; }  struct B { A a; };",
1359               fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
1360 }
1361 
TEST_P(ASTMatchersTest,HasOverloadedOperatorName)1362 TEST_P(ASTMatchersTest, HasOverloadedOperatorName) {
1363   if (!GetParam().isCXX()) {
1364     return;
1365   }
1366 
1367   StatementMatcher OpCallAndAnd =
1368       cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
1369   EXPECT_TRUE(matches("class Y { }; "
1370                       "bool operator&&(Y x, Y y) { return true; }; "
1371                       "Y a; Y b; bool c = a && b;",
1372                       OpCallAndAnd));
1373   StatementMatcher OpCallLessLess =
1374       cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
1375   EXPECT_TRUE(notMatches("class Y { }; "
1376                          "bool operator&&(Y x, Y y) { return true; }; "
1377                          "Y a; Y b; bool c = a && b;",
1378                          OpCallLessLess));
1379   StatementMatcher OpStarCall =
1380       cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
1381   EXPECT_TRUE(
1382       matches("class Y; int operator*(Y &); void f(Y &y) { *y; }", OpStarCall));
1383   DeclarationMatcher ClassWithOpStar =
1384       cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
1385   EXPECT_TRUE(matches("class Y { int operator*(); };", ClassWithOpStar));
1386   EXPECT_TRUE(notMatches("class Y { void myOperator(); };", ClassWithOpStar));
1387   DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1388   EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1389   EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
1390   DeclarationMatcher AnyAndOp =
1391       functionDecl(hasAnyOverloadedOperatorName("&", "&&"));
1392   EXPECT_TRUE(matches("class Y; Y operator&(Y &, Y &);", AnyAndOp));
1393   EXPECT_TRUE(matches("class Y; Y operator&&(Y &, Y &);", AnyAndOp));
1394   EXPECT_TRUE(matches("class Y { Y operator&(Y &); };", AnyAndOp));
1395   EXPECT_TRUE(matches("class Y { Y operator&&(Y &); };", AnyAndOp));
1396 }
1397 
TEST_P(ASTMatchersTest,HasOverloadedOperatorName_MatchesNestedCalls)1398 TEST_P(ASTMatchersTest, HasOverloadedOperatorName_MatchesNestedCalls) {
1399   if (!GetParam().isCXX()) {
1400     return;
1401   }
1402 
1403   EXPECT_TRUE(matchAndVerifyResultTrue(
1404       "class Y { }; "
1405       "Y& operator&&(Y& x, Y& y) { return x; }; "
1406       "Y a; Y b; Y c; Y d = a && b && c;",
1407       cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1408       std::make_unique<VerifyIdIsBoundTo<CXXOperatorCallExpr>>("x", 2)));
1409   EXPECT_TRUE(matches("class Y { }; "
1410                       "Y& operator&&(Y& x, Y& y) { return x; }; "
1411                       "Y a; Y b; Y c; Y d = a && b && c;",
1412                       cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
1413   EXPECT_TRUE(
1414       matches("class Y { }; "
1415               "Y& operator&&(Y& x, Y& y) { return x; }; "
1416               "Y a; Y b; Y c; Y d = a && b && c;",
1417               cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
1418 }
1419 
TEST_P(ASTMatchersTest,HasLocalStorage)1420 TEST_P(ASTMatchersTest, HasLocalStorage) {
1421   auto M = varDecl(hasName("X"), hasLocalStorage());
1422   EXPECT_TRUE(matches("void f() { int X; }", M));
1423   EXPECT_TRUE(notMatches("int X;", M));
1424   EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1425 }
1426 
TEST_P(ASTMatchersTest,HasGlobalStorage)1427 TEST_P(ASTMatchersTest, HasGlobalStorage) {
1428   auto M = varDecl(hasName("X"), hasGlobalStorage());
1429   EXPECT_TRUE(notMatches("void f() { int X; }", M));
1430   EXPECT_TRUE(matches("int X;", M));
1431   EXPECT_TRUE(matches("void f() { static int X; }", M));
1432 }
1433 
TEST_P(ASTMatchersTest,IsStaticLocal)1434 TEST_P(ASTMatchersTest, IsStaticLocal) {
1435   auto M = varDecl(isStaticLocal());
1436   EXPECT_TRUE(matches("void f() { static int X; }", M));
1437   EXPECT_TRUE(notMatches("static int X;", M));
1438   EXPECT_TRUE(notMatches("void f() { int X; }", M));
1439   EXPECT_TRUE(notMatches("int X;", M));
1440 }
1441 
TEST_P(ASTMatchersTest,StorageDuration)1442 TEST_P(ASTMatchersTest, StorageDuration) {
1443   StringRef T =
1444       "void f() { int x; static int y; } int a;static int b;extern int c;";
1445 
1446   EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
1447   EXPECT_TRUE(
1448       notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
1449   EXPECT_TRUE(
1450       notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
1451 
1452   EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
1453   EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
1454   EXPECT_TRUE(matches(T, varDecl(hasName("b"), hasStaticStorageDuration())));
1455   EXPECT_TRUE(matches(T, varDecl(hasName("c"), hasStaticStorageDuration())));
1456   EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
1457 
1458   // FIXME: Add thread_local variables to the source code snippet.
1459   EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
1460   EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
1461   EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
1462 }
1463 
TEST_P(ASTMatchersTest,VarDecl_MatchesFunctionParameter)1464 TEST_P(ASTMatchersTest, VarDecl_MatchesFunctionParameter) {
1465   EXPECT_TRUE(matches("void f(int i) {}", varDecl(hasName("i"))));
1466 }
1467 
TEST_P(ASTMatchersTest,SizeOfExpr_MatchesCorrectType)1468 TEST_P(ASTMatchersTest, SizeOfExpr_MatchesCorrectType) {
1469   EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1470                       sizeOfExpr(hasArgumentOfType(asString("int")))));
1471   EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1472                          sizeOfExpr(hasArgumentOfType(asString("float")))));
1473   EXPECT_TRUE(matches(
1474       "struct A {}; void x() { struct A a; int b = sizeof(a); }",
1475       sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
1476   EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1477                          sizeOfExpr(hasArgumentOfType(
1478                              hasDeclaration(recordDecl(hasName("string")))))));
1479 }
1480 
TEST_P(ASTMatchersTest,IsInteger_MatchesIntegers)1481 TEST_P(ASTMatchersTest, IsInteger_MatchesIntegers) {
1482   EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1483   EXPECT_TRUE(
1484       matches("long long i = 0; void f(long long) { }; void g() {f(i);}",
1485               callExpr(hasArgument(
1486                   0, declRefExpr(to(varDecl(hasType(isInteger()))))))));
1487 }
1488 
TEST_P(ASTMatchersTest,IsInteger_ReportsNoFalsePositives)1489 TEST_P(ASTMatchersTest, IsInteger_ReportsNoFalsePositives) {
1490   if (!GetParam().isCXX()) {
1491     // FIXME: Add a similar negative test for `isInteger()` that does not depend
1492     // on C++.
1493     return;
1494   }
1495 
1496   EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
1497   EXPECT_TRUE(
1498       notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
1499                  callExpr(hasArgument(
1500                      0, declRefExpr(to(varDecl(hasType(isInteger()))))))));
1501 }
1502 
TEST_P(ASTMatchersTest,IsSignedInteger_MatchesSignedIntegers)1503 TEST_P(ASTMatchersTest, IsSignedInteger_MatchesSignedIntegers) {
1504   EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isSignedInteger()))));
1505   EXPECT_TRUE(
1506       notMatches("unsigned i = 0;", varDecl(hasType(isSignedInteger()))));
1507 }
1508 
TEST_P(ASTMatchersTest,IsUnsignedInteger_MatchesUnsignedIntegers)1509 TEST_P(ASTMatchersTest, IsUnsignedInteger_MatchesUnsignedIntegers) {
1510   EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isUnsignedInteger()))));
1511   EXPECT_TRUE(
1512       matches("unsigned i = 0;", varDecl(hasType(isUnsignedInteger()))));
1513 }
1514 
TEST_P(ASTMatchersTest,IsAnyPointer_MatchesPointers)1515 TEST_P(ASTMatchersTest, IsAnyPointer_MatchesPointers) {
1516   if (!GetParam().isCXX11OrLater()) {
1517     // FIXME: Add a test for `isAnyPointer()` that does not depend on C++.
1518     return;
1519   }
1520 
1521   EXPECT_TRUE(matches("int* i = nullptr;", varDecl(hasType(isAnyPointer()))));
1522 }
1523 
TEST_P(ASTMatchersTest,IsAnyPointer_MatchesObjcPointer)1524 TEST_P(ASTMatchersTest, IsAnyPointer_MatchesObjcPointer) {
1525   EXPECT_TRUE(matchesObjC("@interface Foo @end Foo *f;",
1526                           varDecl(hasType(isAnyPointer()))));
1527 }
1528 
TEST_P(ASTMatchersTest,IsAnyPointer_ReportsNoFalsePositives)1529 TEST_P(ASTMatchersTest, IsAnyPointer_ReportsNoFalsePositives) {
1530   EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isAnyPointer()))));
1531 }
1532 
TEST_P(ASTMatchersTest,IsAnyCharacter_MatchesCharacters)1533 TEST_P(ASTMatchersTest, IsAnyCharacter_MatchesCharacters) {
1534   EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
1535 }
1536 
TEST_P(ASTMatchersTest,IsAnyCharacter_ReportsNoFalsePositives)1537 TEST_P(ASTMatchersTest, IsAnyCharacter_ReportsNoFalsePositives) {
1538   EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
1539 }
1540 
TEST_P(ASTMatchersTest,IsArrow_MatchesMemberVariablesViaArrow)1541 TEST_P(ASTMatchersTest, IsArrow_MatchesMemberVariablesViaArrow) {
1542   if (!GetParam().isCXX()) {
1543     // FIXME: Add a test for `isArrow()` that does not depend on C++.
1544     return;
1545   }
1546   if (GetParam().hasDelayedTemplateParsing()) {
1547     // FIXME: Fix this test to work with delayed template parsing.
1548     return;
1549   }
1550 
1551   EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
1552                       memberExpr(isArrow())));
1553   EXPECT_TRUE(
1554       matches("class Y { void x() { y; } int y; };", memberExpr(isArrow())));
1555   EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
1556                          memberExpr(isArrow())));
1557   EXPECT_TRUE(matches("template <class T> class Y { void x() { this->m; } };",
1558                       cxxDependentScopeMemberExpr(isArrow())));
1559   EXPECT_TRUE(
1560       notMatches("template <class T> class Y { void x() { (*this).m; } };",
1561                  cxxDependentScopeMemberExpr(isArrow())));
1562 }
1563 
TEST_P(ASTMatchersTest,IsArrow_MatchesStaticMemberVariablesViaArrow)1564 TEST_P(ASTMatchersTest, IsArrow_MatchesStaticMemberVariablesViaArrow) {
1565   if (!GetParam().isCXX()) {
1566     // FIXME: Add a test for `isArrow()` that does not depend on C++.
1567     return;
1568   }
1569 
1570   EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
1571                       memberExpr(isArrow())));
1572   EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
1573                          memberExpr(isArrow())));
1574   EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
1575                          memberExpr(isArrow())));
1576 }
1577 
TEST_P(ASTMatchersTest,IsArrow_MatchesMemberCallsViaArrow)1578 TEST_P(ASTMatchersTest, IsArrow_MatchesMemberCallsViaArrow) {
1579   if (!GetParam().isCXX()) {
1580     // FIXME: Add a test for `isArrow()` that does not depend on C++.
1581     return;
1582   }
1583   if (GetParam().hasDelayedTemplateParsing()) {
1584     // FIXME: Fix this test to work with delayed template parsing.
1585     return;
1586   }
1587 
1588   EXPECT_TRUE(
1589       matches("class Y { void x() { this->x(); } };", memberExpr(isArrow())));
1590   EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr(isArrow())));
1591   EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
1592                          memberExpr(isArrow())));
1593   EXPECT_TRUE(
1594       matches("class Y { template <class T> void x() { this->x<T>(); } };",
1595               unresolvedMemberExpr(isArrow())));
1596   EXPECT_TRUE(matches("class Y { template <class T> void x() { x<T>(); } };",
1597                       unresolvedMemberExpr(isArrow())));
1598   EXPECT_TRUE(
1599       notMatches("class Y { template <class T> void x() { (*this).x<T>(); } };",
1600                  unresolvedMemberExpr(isArrow())));
1601 }
1602 
TEST_P(ASTMatchersTest,IsExplicit_CXXConversionDecl)1603 TEST_P(ASTMatchersTest, IsExplicit_CXXConversionDecl) {
1604   if (!GetParam().isCXX11OrLater()) {
1605     return;
1606   }
1607 
1608   EXPECT_TRUE(matches("struct S { explicit operator int(); };",
1609                       cxxConversionDecl(isExplicit())));
1610   EXPECT_TRUE(notMatches("struct S { operator int(); };",
1611                          cxxConversionDecl(isExplicit())));
1612 }
1613 
TEST_P(ASTMatchersTest,IsExplicit_CXXConversionDecl_CXX20)1614 TEST_P(ASTMatchersTest, IsExplicit_CXXConversionDecl_CXX20) {
1615   if (!GetParam().isCXX20OrLater()) {
1616     return;
1617   }
1618 
1619   EXPECT_TRUE(
1620       notMatches("template<bool b> struct S { explicit(b) operator int(); };",
1621                  cxxConversionDecl(isExplicit())));
1622   EXPECT_TRUE(matches("struct S { explicit(true) operator int(); };",
1623                       cxxConversionDecl(isExplicit())));
1624   EXPECT_TRUE(notMatches("struct S { explicit(false) operator int(); };",
1625                          cxxConversionDecl(isExplicit())));
1626 }
1627 
TEST_P(ASTMatchersTest,ArgumentCountIs_CallExpr)1628 TEST_P(ASTMatchersTest, ArgumentCountIs_CallExpr) {
1629   StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
1630 
1631   EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1632   EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1633 }
1634 
TEST_P(ASTMatchersTest,ArgumentCountIs_CallExpr_CXX)1635 TEST_P(ASTMatchersTest, ArgumentCountIs_CallExpr_CXX) {
1636   if (!GetParam().isCXX()) {
1637     return;
1638   }
1639 
1640   StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
1641   EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1642 }
1643 
TEST_P(ASTMatchersTest,ParameterCountIs)1644 TEST_P(ASTMatchersTest, ParameterCountIs) {
1645   DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1646   EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1647   EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1648   EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1649   EXPECT_TRUE(matches("void f(int i, ...) {};", Function1Arg));
1650 }
1651 
TEST_P(ASTMatchersTest,ParameterCountIs_CXX)1652 TEST_P(ASTMatchersTest, ParameterCountIs_CXX) {
1653   if (!GetParam().isCXX()) {
1654     return;
1655   }
1656 
1657   DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1658   EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1659 }
1660 
TEST_P(ASTMatchersTest,References)1661 TEST_P(ASTMatchersTest, References) {
1662   if (!GetParam().isCXX()) {
1663     // FIXME: Add a test for `references()` that does not depend on C++.
1664     return;
1665   }
1666 
1667   DeclarationMatcher ReferenceClassX =
1668       varDecl(hasType(references(recordDecl(hasName("X")))));
1669   EXPECT_TRUE(
1670       matches("class X {}; void y(X y) { X &x = y; }", ReferenceClassX));
1671   EXPECT_TRUE(
1672       matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
1673   // The match here is on the implicit copy constructor code for
1674   // class X, not on code 'X x = y'.
1675   EXPECT_TRUE(matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1676   EXPECT_TRUE(notMatches("class X {}; extern X x;", ReferenceClassX));
1677   EXPECT_TRUE(
1678       notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1679 }
1680 
TEST_P(ASTMatchersTest,HasLocalQualifiers)1681 TEST_P(ASTMatchersTest, HasLocalQualifiers) {
1682   if (!GetParam().isCXX11OrLater()) {
1683     // FIXME: Add a test for `hasLocalQualifiers()` that does not depend on C++.
1684     return;
1685   }
1686 
1687   EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1688                          varDecl(hasType(hasLocalQualifiers()))));
1689   EXPECT_TRUE(matches("int *const j = nullptr;",
1690                       varDecl(hasType(hasLocalQualifiers()))));
1691   EXPECT_TRUE(
1692       matches("int *volatile k;", varDecl(hasType(hasLocalQualifiers()))));
1693   EXPECT_TRUE(notMatches("int m;", varDecl(hasType(hasLocalQualifiers()))));
1694 }
1695 
TEST_P(ASTMatchersTest,IsExternC_MatchesExternCFunctionDeclarations)1696 TEST_P(ASTMatchersTest, IsExternC_MatchesExternCFunctionDeclarations) {
1697   if (!GetParam().isCXX()) {
1698     return;
1699   }
1700 
1701   EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1702   EXPECT_TRUE(
1703       matches("extern \"C\" { void f() {} }", functionDecl(isExternC())));
1704   EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
1705 }
1706 
TEST_P(ASTMatchersTest,IsExternC_MatchesExternCVariableDeclarations)1707 TEST_P(ASTMatchersTest, IsExternC_MatchesExternCVariableDeclarations) {
1708   if (!GetParam().isCXX()) {
1709     return;
1710   }
1711 
1712   EXPECT_TRUE(matches("extern \"C\" int i;", varDecl(isExternC())));
1713   EXPECT_TRUE(matches("extern \"C\" { int i; }", varDecl(isExternC())));
1714   EXPECT_TRUE(notMatches("int i;", varDecl(isExternC())));
1715 }
1716 
TEST_P(ASTMatchersTest,IsStaticStorageClass)1717 TEST_P(ASTMatchersTest, IsStaticStorageClass) {
1718   EXPECT_TRUE(
1719       matches("static void f() {}", functionDecl(isStaticStorageClass())));
1720   EXPECT_TRUE(matches("static int i = 1;", varDecl(isStaticStorageClass())));
1721   EXPECT_TRUE(notMatches("int i = 1;", varDecl(isStaticStorageClass())));
1722   EXPECT_TRUE(notMatches("extern int i;", varDecl(isStaticStorageClass())));
1723   EXPECT_TRUE(notMatches("void f() {}", functionDecl(isStaticStorageClass())));
1724 }
1725 
TEST_P(ASTMatchersTest,IsDefaulted)1726 TEST_P(ASTMatchersTest, IsDefaulted) {
1727   if (!GetParam().isCXX()) {
1728     return;
1729   }
1730 
1731   EXPECT_TRUE(notMatches("class A { ~A(); };",
1732                          functionDecl(hasName("~A"), isDefaulted())));
1733   EXPECT_TRUE(matches("class B { ~B() = default; };",
1734                       functionDecl(hasName("~B"), isDefaulted())));
1735 }
1736 
TEST_P(ASTMatchersTest,IsDeleted)1737 TEST_P(ASTMatchersTest, IsDeleted) {
1738   if (!GetParam().isCXX()) {
1739     return;
1740   }
1741 
1742   EXPECT_TRUE(
1743       notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1744   EXPECT_TRUE(matches("void Func() = delete;",
1745                       functionDecl(hasName("Func"), isDeleted())));
1746 }
1747 
TEST_P(ASTMatchersTest,IsNoThrow_DynamicExceptionSpec)1748 TEST_P(ASTMatchersTest, IsNoThrow_DynamicExceptionSpec) {
1749   if (!GetParam().supportsCXXDynamicExceptionSpecification()) {
1750     return;
1751   }
1752 
1753   EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
1754   EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
1755   EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
1756 
1757   EXPECT_TRUE(notMatches("void f();", functionProtoType(isNoThrow())));
1758   EXPECT_TRUE(
1759       notMatches("void f() throw(int);", functionProtoType(isNoThrow())));
1760   EXPECT_TRUE(matches("void f() throw();", functionProtoType(isNoThrow())));
1761 }
1762 
TEST_P(ASTMatchersTest,IsNoThrow_CXX11)1763 TEST_P(ASTMatchersTest, IsNoThrow_CXX11) {
1764   if (!GetParam().isCXX11OrLater()) {
1765     return;
1766   }
1767 
1768   EXPECT_TRUE(
1769       notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
1770   EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
1771 
1772   EXPECT_TRUE(
1773       notMatches("void f() noexcept(false);", functionProtoType(isNoThrow())));
1774   EXPECT_TRUE(matches("void f() noexcept;", functionProtoType(isNoThrow())));
1775 }
1776 
TEST_P(ASTMatchersTest,IsConstexpr)1777 TEST_P(ASTMatchersTest, IsConstexpr) {
1778   if (!GetParam().isCXX11OrLater()) {
1779     return;
1780   }
1781 
1782   EXPECT_TRUE(matches("constexpr int foo = 42;",
1783                       varDecl(hasName("foo"), isConstexpr())));
1784   EXPECT_TRUE(matches("constexpr int bar();",
1785                       functionDecl(hasName("bar"), isConstexpr())));
1786 }
1787 
TEST_P(ASTMatchersTest,IsConstexpr_MatchesIfConstexpr)1788 TEST_P(ASTMatchersTest, IsConstexpr_MatchesIfConstexpr) {
1789   if (!GetParam().isCXX17OrLater()) {
1790     return;
1791   }
1792 
1793   EXPECT_TRUE(
1794       matches("void baz() { if constexpr(1 > 0) {} }", ifStmt(isConstexpr())));
1795   EXPECT_TRUE(
1796       notMatches("void baz() { if (1 > 0) {} }", ifStmt(isConstexpr())));
1797 }
1798 
TEST_P(ASTMatchersTest,HasInitStatement_MatchesSelectionInitializers)1799 TEST_P(ASTMatchersTest, HasInitStatement_MatchesSelectionInitializers) {
1800   EXPECT_TRUE(notMatches("void baz() { if (1 > 0) {} }",
1801                          ifStmt(hasInitStatement(anything()))));
1802   EXPECT_TRUE(notMatches("void baz(int i) { switch (i) { default: break; } }",
1803                          switchStmt(hasInitStatement(anything()))));
1804 }
1805 
TEST_P(ASTMatchersTest,HasInitStatement_MatchesSelectionInitializers_CXX)1806 TEST_P(ASTMatchersTest, HasInitStatement_MatchesSelectionInitializers_CXX) {
1807   if (!GetParam().isCXX()) {
1808     return;
1809   }
1810 
1811   EXPECT_TRUE(notMatches("void baz() { if (int i = 1) {} }",
1812                          ifStmt(hasInitStatement(anything()))));
1813 }
1814 
TEST_P(ASTMatchersTest,HasInitStatement_MatchesSelectionInitializers_CXX17)1815 TEST_P(ASTMatchersTest, HasInitStatement_MatchesSelectionInitializers_CXX17) {
1816   if (!GetParam().isCXX17OrLater()) {
1817     return;
1818   }
1819 
1820   EXPECT_TRUE(matches("void baz() { if (int i = 1; i > 0) {} }",
1821                       ifStmt(hasInitStatement(anything()))));
1822   EXPECT_TRUE(
1823       matches("void baz(int i) { switch (int j = i; j) { default: break; } }",
1824               switchStmt(hasInitStatement(anything()))));
1825 }
1826 
TEST_P(ASTMatchersTest,HasInitStatement_MatchesRangeForInitializers)1827 TEST_P(ASTMatchersTest, HasInitStatement_MatchesRangeForInitializers) {
1828   if (!GetParam().isCXX20OrLater()) {
1829     return;
1830   }
1831 
1832   EXPECT_TRUE(matches("void baz() {"
1833                       "int items[] = {};"
1834                       "for (auto &arr = items; auto &item : arr) {}"
1835                       "}",
1836                       cxxForRangeStmt(hasInitStatement(anything()))));
1837   EXPECT_TRUE(notMatches("void baz() {"
1838                          "int items[] = {};"
1839                          "for (auto &item : items) {}"
1840                          "}",
1841                          cxxForRangeStmt(hasInitStatement(anything()))));
1842 }
1843 
TEST_P(ASTMatchersTest,TemplateArgumentCountIs)1844 TEST_P(ASTMatchersTest, TemplateArgumentCountIs) {
1845   if (!GetParam().isCXX()) {
1846     return;
1847   }
1848 
1849   EXPECT_TRUE(
1850       matches("template<typename T> struct C {}; C<int> c;",
1851               classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1852   EXPECT_TRUE(
1853       notMatches("template<typename T> struct C {}; C<int> c;",
1854                  classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1855 
1856   EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1857                       templateSpecializationType(templateArgumentCountIs(1))));
1858   EXPECT_TRUE(
1859       notMatches("template<typename T> struct C {}; C<int> c;",
1860                  templateSpecializationType(templateArgumentCountIs(2))));
1861 }
1862 
TEST_P(ASTMatchersTest,IsIntegral)1863 TEST_P(ASTMatchersTest, IsIntegral) {
1864   if (!GetParam().isCXX()) {
1865     return;
1866   }
1867 
1868   EXPECT_TRUE(matches(
1869       "template<int T> struct C {}; C<42> c;",
1870       classTemplateSpecializationDecl(hasAnyTemplateArgument(isIntegral()))));
1871   EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1872                          classTemplateSpecializationDecl(hasAnyTemplateArgument(
1873                              templateArgument(isIntegral())))));
1874 }
1875 
TEST_P(ASTMatchersTest,EqualsIntegralValue)1876 TEST_P(ASTMatchersTest, EqualsIntegralValue) {
1877   if (!GetParam().isCXX()) {
1878     return;
1879   }
1880 
1881   EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1882                       classTemplateSpecializationDecl(
1883                           hasAnyTemplateArgument(equalsIntegralValue("42")))));
1884   EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1885                       classTemplateSpecializationDecl(
1886                           hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1887   EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1888                       classTemplateSpecializationDecl(
1889                           hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1890   EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1891                          classTemplateSpecializationDecl(hasAnyTemplateArgument(
1892                              equalsIntegralValue("0042")))));
1893 }
1894 
TEST_P(ASTMatchersTest,AccessSpecDecl)1895 TEST_P(ASTMatchersTest, AccessSpecDecl) {
1896   if (!GetParam().isCXX()) {
1897     return;
1898   }
1899 
1900   EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1901   EXPECT_TRUE(
1902       matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1903   EXPECT_TRUE(
1904       notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1905   EXPECT_TRUE(
1906       notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1907 
1908   EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1909 }
1910 
TEST_P(ASTMatchersTest,IsFinal)1911 TEST_P(ASTMatchersTest, IsFinal) {
1912   if (!GetParam().isCXX11OrLater()) {
1913     return;
1914   }
1915 
1916   EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
1917   EXPECT_TRUE(matches("class X { virtual void f() final; };",
1918                       cxxMethodDecl(isFinal())));
1919   EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
1920   EXPECT_TRUE(
1921       notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
1922 }
1923 
TEST_P(ASTMatchersTest,IsVirtual)1924 TEST_P(ASTMatchersTest, IsVirtual) {
1925   if (!GetParam().isCXX()) {
1926     return;
1927   }
1928 
1929   EXPECT_TRUE(matches("class X { virtual int f(); };",
1930                       cxxMethodDecl(isVirtual(), hasName("::X::f"))));
1931   EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
1932 }
1933 
TEST_P(ASTMatchersTest,IsVirtualAsWritten)1934 TEST_P(ASTMatchersTest, IsVirtualAsWritten) {
1935   if (!GetParam().isCXX()) {
1936     return;
1937   }
1938 
1939   EXPECT_TRUE(matches("class A { virtual int f(); };"
1940                       "class B : public A { int f(); };",
1941                       cxxMethodDecl(isVirtualAsWritten(), hasName("::A::f"))));
1942   EXPECT_TRUE(
1943       notMatches("class A { virtual int f(); };"
1944                  "class B : public A { int f(); };",
1945                  cxxMethodDecl(isVirtualAsWritten(), hasName("::B::f"))));
1946 }
1947 
TEST_P(ASTMatchersTest,IsPure)1948 TEST_P(ASTMatchersTest, IsPure) {
1949   if (!GetParam().isCXX()) {
1950     return;
1951   }
1952 
1953   EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1954                       cxxMethodDecl(isPure(), hasName("::X::f"))));
1955   EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
1956 }
1957 
TEST_P(ASTMatchersTest,IsCopyAssignmentOperator)1958 TEST_P(ASTMatchersTest, IsCopyAssignmentOperator) {
1959   if (!GetParam().isCXX()) {
1960     return;
1961   }
1962 
1963   auto CopyAssignment =
1964       cxxMethodDecl(isCopyAssignmentOperator(), unless(isImplicit()));
1965   EXPECT_TRUE(matches("class X { X &operator=(X); };", CopyAssignment));
1966   EXPECT_TRUE(matches("class X { X &operator=(X &); };", CopyAssignment));
1967   EXPECT_TRUE(matches("class X { X &operator=(const X &); };", CopyAssignment));
1968   EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };", //
1969                       CopyAssignment));
1970   EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
1971                       CopyAssignment));
1972   EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };", CopyAssignment));
1973 }
1974 
TEST_P(ASTMatchersTest,IsMoveAssignmentOperator)1975 TEST_P(ASTMatchersTest, IsMoveAssignmentOperator) {
1976   if (!GetParam().isCXX()) {
1977     return;
1978   }
1979 
1980   auto MoveAssignment =
1981       cxxMethodDecl(isMoveAssignmentOperator(), unless(isImplicit()));
1982   EXPECT_TRUE(notMatches("class X { X &operator=(X); };", MoveAssignment));
1983   EXPECT_TRUE(matches("class X { X &operator=(X &&); };", MoveAssignment));
1984   EXPECT_TRUE(matches("class X { X &operator=(const X &&); };", //
1985                       MoveAssignment));
1986   EXPECT_TRUE(matches("class X { X &operator=(volatile X &&); };", //
1987                       MoveAssignment));
1988   EXPECT_TRUE(matches("class X { X &operator=(const volatile X &&); };",
1989                       MoveAssignment));
1990   EXPECT_TRUE(notMatches("class X { X &operator=(X &); };", MoveAssignment));
1991 }
1992 
TEST_P(ASTMatchersTest,IsConst)1993 TEST_P(ASTMatchersTest, IsConst) {
1994   if (!GetParam().isCXX()) {
1995     return;
1996   }
1997 
1998   EXPECT_TRUE(
1999       matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
2000   EXPECT_TRUE(
2001       notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
2002 }
2003 
TEST_P(ASTMatchersTest,IsOverride)2004 TEST_P(ASTMatchersTest, IsOverride) {
2005   if (!GetParam().isCXX()) {
2006     return;
2007   }
2008 
2009   EXPECT_TRUE(matches("class X { virtual int f(); }; "
2010                       "class Y : public X { int f(); };",
2011                       cxxMethodDecl(isOverride(), hasName("::Y::f"))));
2012   EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
2013                          "class Y : public X { int f(); };",
2014                          cxxMethodDecl(isOverride(), hasName("::X::f"))));
2015   EXPECT_TRUE(notMatches("class X { int f(); }; "
2016                          "class Y : public X { int f(); };",
2017                          cxxMethodDecl(isOverride())));
2018   EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
2019                          cxxMethodDecl(isOverride())));
2020   EXPECT_TRUE(
2021       matches("template <typename Base> struct Y : Base { void f() override;};",
2022               cxxMethodDecl(isOverride(), hasName("::Y::f"))));
2023 }
2024 
TEST_P(ASTMatchersTest,HasArgument_CXXConstructorDecl)2025 TEST_P(ASTMatchersTest, HasArgument_CXXConstructorDecl) {
2026   if (!GetParam().isCXX()) {
2027     return;
2028   }
2029 
2030   auto Constructor = traverse(
2031       TK_AsIs,
2032       cxxConstructExpr(hasArgument(0, declRefExpr(to(varDecl(hasName("y")))))));
2033 
2034   EXPECT_TRUE(matches(
2035       "class X { public: X(int); }; void x() { int y; X x(y); }", Constructor));
2036   EXPECT_TRUE(
2037       matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
2038               Constructor));
2039   EXPECT_TRUE(
2040       matches("class X { public: X(int); }; void x() { int y; X x = y; }",
2041               Constructor));
2042   EXPECT_TRUE(notMatches(
2043       "class X { public: X(int); }; void x() { int z; X x(z); }", Constructor));
2044 
2045   StatementMatcher WrongIndex =
2046       traverse(TK_AsIs, cxxConstructExpr(hasArgument(
2047                             42, declRefExpr(to(varDecl(hasName("y")))))));
2048   EXPECT_TRUE(notMatches(
2049       "class X { public: X(int); }; void x() { int y; X x(y); }", WrongIndex));
2050 }
2051 
TEST_P(ASTMatchersTest,ArgumentCountIs_CXXConstructExpr)2052 TEST_P(ASTMatchersTest, ArgumentCountIs_CXXConstructExpr) {
2053   if (!GetParam().isCXX()) {
2054     return;
2055   }
2056 
2057   auto Constructor1Arg =
2058       traverse(TK_AsIs, cxxConstructExpr(argumentCountIs(1)));
2059 
2060   EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x(0); }",
2061                       Constructor1Arg));
2062   EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = X(0); }",
2063                       Constructor1Arg));
2064   EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = 0; }",
2065                       Constructor1Arg));
2066   EXPECT_TRUE(
2067       notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
2068                  Constructor1Arg));
2069 }
2070 
TEST(ASTMatchersTest,NamesMember_CXXDependentScopeMemberExpr)2071 TEST(ASTMatchersTest, NamesMember_CXXDependentScopeMemberExpr) {
2072 
2073   // Member functions:
2074   {
2075     auto Code = "template <typename T> struct S{ void mem(); }; template "
2076                 "<typename T> void x() { S<T> s; s.mem(); }";
2077 
2078     EXPECT_TRUE(matches(
2079         Code,
2080         cxxDependentScopeMemberExpr(
2081             hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
2082                 hasDeclaration(classTemplateDecl(has(cxxRecordDecl(
2083                     has(cxxMethodDecl(hasName("mem")).bind("templMem")))))))))),
2084             memberHasSameNameAsBoundNode("templMem"))));
2085 
2086     EXPECT_TRUE(
2087         matches(Code, cxxDependentScopeMemberExpr(hasMemberName("mem"))));
2088   }
2089 
2090   // Member variables:
2091   {
2092     auto Code = "template <typename T> struct S{ int mem; }; template "
2093                 "<typename T> void x() { S<T> s; s.mem; }";
2094 
2095     EXPECT_TRUE(
2096         matches(Code, cxxDependentScopeMemberExpr(hasMemberName("mem"))));
2097 
2098     EXPECT_TRUE(matches(
2099         Code,
2100         cxxDependentScopeMemberExpr(
2101             hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
2102                 hasDeclaration(classTemplateDecl(has(cxxRecordDecl(
2103                     has(fieldDecl(hasName("mem")).bind("templMem")))))))))),
2104             memberHasSameNameAsBoundNode("templMem"))));
2105   }
2106 
2107   // static member variables:
2108   {
2109     auto Code = "template <typename T> struct S{ static int mem; }; template "
2110                 "<typename T> void x() { S<T> s; s.mem; }";
2111 
2112     EXPECT_TRUE(
2113         matches(Code, cxxDependentScopeMemberExpr(hasMemberName("mem"))));
2114 
2115     EXPECT_TRUE(matches(
2116         Code,
2117         cxxDependentScopeMemberExpr(
2118             hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
2119                 hasDeclaration(classTemplateDecl(has(cxxRecordDecl(
2120                     has(varDecl(hasName("mem")).bind("templMem")))))))))),
2121             memberHasSameNameAsBoundNode("templMem"))));
2122   }
2123   {
2124     auto Code = R"cpp(
2125 template <typename T>
2126 struct S {
2127   bool operator==(int) const { return true; }
2128 };
2129 
2130 template <typename T>
2131 void func(T t) {
2132   S<T> s;
2133   s.operator==(1);
2134 }
2135 )cpp";
2136 
2137     EXPECT_TRUE(matches(
2138         Code, cxxDependentScopeMemberExpr(hasMemberName("operator=="))));
2139   }
2140 
2141   // other named decl:
2142   {
2143     auto Code = "template <typename T> struct S{ static int mem; }; struct "
2144                 "mem{}; template "
2145                 "<typename T> void x() { S<T> s; s.mem; }";
2146 
2147     EXPECT_TRUE(matches(
2148         Code,
2149         translationUnitDecl(has(cxxRecordDecl(hasName("mem"))),
2150                             hasDescendant(cxxDependentScopeMemberExpr()))));
2151 
2152     EXPECT_FALSE(matches(
2153         Code,
2154         translationUnitDecl(has(cxxRecordDecl(hasName("mem")).bind("templMem")),
2155                             hasDescendant(cxxDependentScopeMemberExpr(
2156                                 memberHasSameNameAsBoundNode("templMem"))))));
2157   }
2158 }
2159 
TEST(ASTMatchersTest,ArgumentCountIs_CXXUnresolvedConstructExpr)2160 TEST(ASTMatchersTest, ArgumentCountIs_CXXUnresolvedConstructExpr) {
2161   const auto *Code =
2162       "template <typename T> struct S{}; template <typename T> void "
2163       "x() { auto s = S<T>(); }";
2164 
2165   EXPECT_TRUE(matches(Code, cxxUnresolvedConstructExpr(argumentCountIs(0))));
2166   EXPECT_TRUE(notMatches(Code, cxxUnresolvedConstructExpr(argumentCountIs(1))));
2167 }
2168 
TEST(ASTMatchersTest,HasArgument_CXXUnresolvedConstructExpr)2169 TEST(ASTMatchersTest, HasArgument_CXXUnresolvedConstructExpr) {
2170   const auto *Code =
2171       "template <typename T> struct S{ S(int){} }; template <typename "
2172       "T> void x() { int y; auto s = S<T>(y); }";
2173   EXPECT_TRUE(matches(Code, cxxUnresolvedConstructExpr(hasArgument(
2174                                 0, declRefExpr(to(varDecl(hasName("y"))))))));
2175   EXPECT_TRUE(
2176       notMatches(Code, cxxUnresolvedConstructExpr(hasArgument(
2177                            0, declRefExpr(to(varDecl(hasName("x"))))))));
2178 }
2179 
TEST_P(ASTMatchersTest,IsListInitialization)2180 TEST_P(ASTMatchersTest, IsListInitialization) {
2181   if (!GetParam().isCXX11OrLater()) {
2182     return;
2183   }
2184 
2185   auto ConstructorListInit =
2186       traverse(TK_AsIs, varDecl(has(cxxConstructExpr(isListInitialization()))));
2187 
2188   EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x{0}; }",
2189                       ConstructorListInit));
2190   EXPECT_FALSE(matches("class X { public: X(int); }; void x() { X x(0); }",
2191                        ConstructorListInit));
2192 }
2193 
TEST_P(ASTMatchersTest,IsImplicit_CXXConstructorDecl)2194 TEST_P(ASTMatchersTest, IsImplicit_CXXConstructorDecl) {
2195   if (!GetParam().isCXX()) {
2196     return;
2197   }
2198 
2199   // This one doesn't match because the constructor is not added by the
2200   // compiler (it is not needed).
2201   EXPECT_TRUE(notMatches("class Foo { };", cxxConstructorDecl(isImplicit())));
2202   // The compiler added the implicit default constructor.
2203   EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
2204                       cxxConstructorDecl(isImplicit())));
2205   EXPECT_TRUE(matches("class Foo { Foo(){} };",
2206                       cxxConstructorDecl(unless(isImplicit()))));
2207   // The compiler added an implicit assignment operator.
2208   EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
2209                       cxxMethodDecl(isImplicit(), hasName("operator="))));
2210 }
2211 
TEST_P(ASTMatchersTest,IsExplicit_CXXConstructorDecl)2212 TEST_P(ASTMatchersTest, IsExplicit_CXXConstructorDecl) {
2213   if (!GetParam().isCXX()) {
2214     return;
2215   }
2216 
2217   EXPECT_TRUE(matches("struct S { explicit S(int); };",
2218                       cxxConstructorDecl(isExplicit())));
2219   EXPECT_TRUE(
2220       notMatches("struct S { S(int); };", cxxConstructorDecl(isExplicit())));
2221 }
2222 
TEST_P(ASTMatchersTest,IsExplicit_CXXConstructorDecl_CXX20)2223 TEST_P(ASTMatchersTest, IsExplicit_CXXConstructorDecl_CXX20) {
2224   if (!GetParam().isCXX20OrLater()) {
2225     return;
2226   }
2227 
2228   EXPECT_TRUE(notMatches("template<bool b> struct S { explicit(b) S(int);};",
2229                          cxxConstructorDecl(isExplicit())));
2230   EXPECT_TRUE(matches("struct S { explicit(true) S(int);};",
2231                       cxxConstructorDecl(isExplicit())));
2232   EXPECT_TRUE(notMatches("struct S { explicit(false) S(int);};",
2233                          cxxConstructorDecl(isExplicit())));
2234 }
2235 
TEST_P(ASTMatchersTest,IsExplicit_CXXDeductionGuideDecl)2236 TEST_P(ASTMatchersTest, IsExplicit_CXXDeductionGuideDecl) {
2237   if (!GetParam().isCXX17OrLater()) {
2238     return;
2239   }
2240 
2241   EXPECT_TRUE(notMatches("template<typename T> struct S { S(int);};"
2242                          "S(int) -> S<int>;",
2243                          cxxDeductionGuideDecl(isExplicit())));
2244   EXPECT_TRUE(matches("template<typename T> struct S { S(int);};"
2245                       "explicit S(int) -> S<int>;",
2246                       cxxDeductionGuideDecl(isExplicit())));
2247 }
2248 
TEST_P(ASTMatchersTest,IsExplicit_CXXDeductionGuideDecl_CXX20)2249 TEST_P(ASTMatchersTest, IsExplicit_CXXDeductionGuideDecl_CXX20) {
2250   if (!GetParam().isCXX20OrLater()) {
2251     return;
2252   }
2253 
2254   EXPECT_TRUE(matches("template<typename T> struct S { S(int);};"
2255                       "explicit(true) S(int) -> S<int>;",
2256                       cxxDeductionGuideDecl(isExplicit())));
2257   EXPECT_TRUE(notMatches("template<typename T> struct S { S(int);};"
2258                          "explicit(false) S(int) -> S<int>;",
2259                          cxxDeductionGuideDecl(isExplicit())));
2260   EXPECT_TRUE(
2261       notMatches("template<typename T> struct S { S(int);};"
2262                  "template<bool b = true> explicit(b) S(int) -> S<int>;",
2263                  cxxDeductionGuideDecl(isExplicit())));
2264 }
2265 
TEST_P(ASTMatchersTest,CXXConstructorDecl_Kinds)2266 TEST_P(ASTMatchersTest, CXXConstructorDecl_Kinds) {
2267   if (!GetParam().isCXX()) {
2268     return;
2269   }
2270 
2271   EXPECT_TRUE(
2272       matches("struct S { S(); };", cxxConstructorDecl(isDefaultConstructor(),
2273                                                        unless(isImplicit()))));
2274   EXPECT_TRUE(notMatches(
2275       "struct S { S(); };",
2276       cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
2277   EXPECT_TRUE(notMatches(
2278       "struct S { S(); };",
2279       cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
2280 
2281   EXPECT_TRUE(notMatches(
2282       "struct S { S(const S&); };",
2283       cxxConstructorDecl(isDefaultConstructor(), unless(isImplicit()))));
2284   EXPECT_TRUE(
2285       matches("struct S { S(const S&); };",
2286               cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
2287   EXPECT_TRUE(notMatches(
2288       "struct S { S(const S&); };",
2289       cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
2290 
2291   EXPECT_TRUE(notMatches(
2292       "struct S { S(S&&); };",
2293       cxxConstructorDecl(isDefaultConstructor(), unless(isImplicit()))));
2294   EXPECT_TRUE(notMatches(
2295       "struct S { S(S&&); };",
2296       cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
2297   EXPECT_TRUE(
2298       matches("struct S { S(S&&); };",
2299               cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
2300 }
2301 
TEST_P(ASTMatchersTest,IsUserProvided)2302 TEST_P(ASTMatchersTest, IsUserProvided) {
2303   if (!GetParam().isCXX11OrLater()) {
2304     return;
2305   }
2306 
2307   EXPECT_TRUE(notMatches("struct S { int X = 0; };",
2308                          cxxConstructorDecl(isUserProvided())));
2309   EXPECT_TRUE(notMatches("struct S { S() = default; };",
2310                          cxxConstructorDecl(isUserProvided())));
2311   EXPECT_TRUE(notMatches("struct S { S() = delete; };",
2312                          cxxConstructorDecl(isUserProvided())));
2313   EXPECT_TRUE(
2314       matches("struct S { S(); };", cxxConstructorDecl(isUserProvided())));
2315   EXPECT_TRUE(matches("struct S { S(); }; S::S(){}",
2316                       cxxConstructorDecl(isUserProvided())));
2317 }
2318 
TEST_P(ASTMatchersTest,IsDelegatingConstructor)2319 TEST_P(ASTMatchersTest, IsDelegatingConstructor) {
2320   if (!GetParam().isCXX11OrLater()) {
2321     return;
2322   }
2323 
2324   EXPECT_TRUE(notMatches("struct S { S(); S(int); int X; };",
2325                          cxxConstructorDecl(isDelegatingConstructor())));
2326   EXPECT_TRUE(notMatches("struct S { S(){} S(int X) : X(X) {} int X; };",
2327                          cxxConstructorDecl(isDelegatingConstructor())));
2328   EXPECT_TRUE(matches(
2329       "struct S { S() : S(0) {} S(int X) : X(X) {} int X; };",
2330       cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(0))));
2331   EXPECT_TRUE(matches(
2332       "struct S { S(); S(int X); int X; }; S::S(int X) : S() {}",
2333       cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(1))));
2334 }
2335 
TEST_P(ASTMatchersTest,HasSize)2336 TEST_P(ASTMatchersTest, HasSize) {
2337   StatementMatcher Literal = stringLiteral(hasSize(4));
2338   EXPECT_TRUE(matches("const char *s = \"abcd\";", Literal));
2339   // with escaped characters
2340   EXPECT_TRUE(matches("const char *s = \"\x05\x06\x07\x08\";", Literal));
2341   // no matching, too small
2342   EXPECT_TRUE(notMatches("const char *s = \"ab\";", Literal));
2343 }
2344 
TEST_P(ASTMatchersTest,HasSize_CXX)2345 TEST_P(ASTMatchersTest, HasSize_CXX) {
2346   if (!GetParam().isCXX()) {
2347     // FIXME: Fix this test to also work in non-C++ language modes.
2348     return;
2349   }
2350 
2351   StatementMatcher Literal = stringLiteral(hasSize(4));
2352   // wide string
2353   EXPECT_TRUE(matches("const wchar_t *s = L\"abcd\";", Literal));
2354 }
2355 
TEST_P(ASTMatchersTest,HasName_MatchesNamespaces)2356 TEST_P(ASTMatchersTest, HasName_MatchesNamespaces) {
2357   if (!GetParam().isCXX()) {
2358     return;
2359   }
2360 
2361   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2362                       recordDecl(hasName("a::b::C"))));
2363   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2364                       recordDecl(hasName("::a::b::C"))));
2365   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2366                       recordDecl(hasName("b::C"))));
2367   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2368                       recordDecl(hasName("C"))));
2369   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2370                          recordDecl(hasName("c::b::C"))));
2371   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2372                          recordDecl(hasName("a::c::C"))));
2373   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2374                          recordDecl(hasName("a::b::A"))));
2375   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2376                          recordDecl(hasName("::C"))));
2377   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2378                          recordDecl(hasName("::b::C"))));
2379   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2380                          recordDecl(hasName("z::a::b::C"))));
2381   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2382                          recordDecl(hasName("a+b::C"))));
2383   EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
2384                          recordDecl(hasName("C"))));
2385 }
2386 
TEST_P(ASTMatchersTest,HasName_MatchesOuterClasses)2387 TEST_P(ASTMatchersTest, HasName_MatchesOuterClasses) {
2388   if (!GetParam().isCXX()) {
2389     return;
2390   }
2391 
2392   EXPECT_TRUE(matches("class A { class B { class C; }; };",
2393                       recordDecl(hasName("A::B::C"))));
2394   EXPECT_TRUE(matches("class A { class B { class C; }; };",
2395                       recordDecl(hasName("::A::B::C"))));
2396   EXPECT_TRUE(matches("class A { class B { class C; }; };",
2397                       recordDecl(hasName("B::C"))));
2398   EXPECT_TRUE(
2399       matches("class A { class B { class C; }; };", recordDecl(hasName("C"))));
2400   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2401                          recordDecl(hasName("c::B::C"))));
2402   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2403                          recordDecl(hasName("A::c::C"))));
2404   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2405                          recordDecl(hasName("A::B::A"))));
2406   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2407                          recordDecl(hasName("::C"))));
2408   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2409                          recordDecl(hasName("::B::C"))));
2410   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2411                          recordDecl(hasName("z::A::B::C"))));
2412   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2413                          recordDecl(hasName("A+B::C"))));
2414 }
2415 
TEST_P(ASTMatchersTest,HasName_MatchesInlinedNamespaces)2416 TEST_P(ASTMatchersTest, HasName_MatchesInlinedNamespaces) {
2417   if (!GetParam().isCXX()) {
2418     return;
2419   }
2420 
2421   StringRef code = "namespace a { inline namespace b { class C; } }";
2422   EXPECT_TRUE(matches(code, recordDecl(hasName("a::b::C"))));
2423   EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
2424   EXPECT_TRUE(matches(code, recordDecl(hasName("::a::b::C"))));
2425   EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
2426 }
2427 
TEST_P(ASTMatchersTest,HasName_MatchesAnonymousNamespaces)2428 TEST_P(ASTMatchersTest, HasName_MatchesAnonymousNamespaces) {
2429   if (!GetParam().isCXX()) {
2430     return;
2431   }
2432 
2433   StringRef code = "namespace a { namespace { class C; } }";
2434   EXPECT_TRUE(
2435       matches(code, recordDecl(hasName("a::(anonymous namespace)::C"))));
2436   EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
2437   EXPECT_TRUE(
2438       matches(code, recordDecl(hasName("::a::(anonymous namespace)::C"))));
2439   EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
2440 }
2441 
TEST_P(ASTMatchersTest,HasName_MatchesAnonymousOuterClasses)2442 TEST_P(ASTMatchersTest, HasName_MatchesAnonymousOuterClasses) {
2443   if (!GetParam().isCXX()) {
2444     return;
2445   }
2446 
2447   EXPECT_TRUE(matches("class A { class { class C; } x; };",
2448                       recordDecl(hasName("A::(anonymous class)::C"))));
2449   EXPECT_TRUE(matches("class A { class { class C; } x; };",
2450                       recordDecl(hasName("::A::(anonymous class)::C"))));
2451   EXPECT_FALSE(matches("class A { class { class C; } x; };",
2452                        recordDecl(hasName("::A::C"))));
2453   EXPECT_TRUE(matches("class A { struct { class C; } x; };",
2454                       recordDecl(hasName("A::(anonymous struct)::C"))));
2455   EXPECT_TRUE(matches("class A { struct { class C; } x; };",
2456                       recordDecl(hasName("::A::(anonymous struct)::C"))));
2457   EXPECT_FALSE(matches("class A { struct { class C; } x; };",
2458                        recordDecl(hasName("::A::C"))));
2459 }
2460 
TEST_P(ASTMatchersTest,HasName_MatchesFunctionScope)2461 TEST_P(ASTMatchersTest, HasName_MatchesFunctionScope) {
2462   if (!GetParam().isCXX()) {
2463     return;
2464   }
2465 
2466   StringRef code =
2467       "namespace a { void F(int a) { struct S { int m; }; int i; } }";
2468   EXPECT_TRUE(matches(code, varDecl(hasName("i"))));
2469   EXPECT_FALSE(matches(code, varDecl(hasName("F()::i"))));
2470 
2471   EXPECT_TRUE(matches(code, fieldDecl(hasName("m"))));
2472   EXPECT_TRUE(matches(code, fieldDecl(hasName("S::m"))));
2473   EXPECT_TRUE(matches(code, fieldDecl(hasName("F(int)::S::m"))));
2474   EXPECT_TRUE(matches(code, fieldDecl(hasName("a::F(int)::S::m"))));
2475   EXPECT_TRUE(matches(code, fieldDecl(hasName("::a::F(int)::S::m"))));
2476 }
2477 
TEST_P(ASTMatchersTest,HasName_QualifiedStringMatchesThroughLinkage)2478 TEST_P(ASTMatchersTest, HasName_QualifiedStringMatchesThroughLinkage) {
2479   if (!GetParam().isCXX()) {
2480     return;
2481   }
2482 
2483   // https://bugs.llvm.org/show_bug.cgi?id=42193
2484   StringRef code = R"cpp(namespace foo { extern "C" void test(); })cpp";
2485   EXPECT_TRUE(matches(code, functionDecl(hasName("test"))));
2486   EXPECT_TRUE(matches(code, functionDecl(hasName("foo::test"))));
2487   EXPECT_TRUE(matches(code, functionDecl(hasName("::foo::test"))));
2488   EXPECT_TRUE(notMatches(code, functionDecl(hasName("::test"))));
2489 
2490   code = R"cpp(namespace foo { extern "C" { void test(); } })cpp";
2491   EXPECT_TRUE(matches(code, functionDecl(hasName("test"))));
2492   EXPECT_TRUE(matches(code, functionDecl(hasName("foo::test"))));
2493   EXPECT_TRUE(matches(code, functionDecl(hasName("::foo::test"))));
2494   EXPECT_TRUE(notMatches(code, functionDecl(hasName("::test"))));
2495 }
2496 
TEST_P(ASTMatchersTest,HasAnyName)2497 TEST_P(ASTMatchersTest, HasAnyName) {
2498   if (!GetParam().isCXX()) {
2499     // FIXME: Add a test for `hasAnyName()` that does not depend on C++.
2500     return;
2501   }
2502 
2503   StringRef Code = "namespace a { namespace b { class C; } }";
2504 
2505   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "a::b::C"))));
2506   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("a::b::C", "XX"))));
2507   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX::C", "a::b::C"))));
2508   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "C"))));
2509 
2510   EXPECT_TRUE(notMatches(Code, recordDecl(hasAnyName("::C", "::b::C"))));
2511   EXPECT_TRUE(
2512       matches(Code, recordDecl(hasAnyName("::C", "::b::C", "::a::b::C"))));
2513 
2514   std::vector<StringRef> Names = {"::C", "::b::C", "::a::b::C"};
2515   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName(Names))));
2516 }
2517 
TEST_P(ASTMatchersTest,IsDefinition)2518 TEST_P(ASTMatchersTest, IsDefinition) {
2519   DeclarationMatcher DefinitionOfClassA =
2520       recordDecl(hasName("A"), isDefinition());
2521   EXPECT_TRUE(matches("struct A {};", DefinitionOfClassA));
2522   EXPECT_TRUE(notMatches("struct A;", DefinitionOfClassA));
2523 
2524   DeclarationMatcher DefinitionOfVariableA =
2525       varDecl(hasName("a"), isDefinition());
2526   EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2527   EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2528 }
2529 
TEST_P(ASTMatchersTest,IsDefinition_CXX)2530 TEST_P(ASTMatchersTest, IsDefinition_CXX) {
2531   if (!GetParam().isCXX()) {
2532     return;
2533   }
2534 
2535   DeclarationMatcher DefinitionOfMethodA =
2536       cxxMethodDecl(hasName("a"), isDefinition());
2537   EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2538   EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2539 
2540   DeclarationMatcher DefinitionOfObjCMethodA =
2541       objcMethodDecl(hasName("a"), isDefinition());
2542   EXPECT_TRUE(matchesObjC("@interface A @end "
2543                           "@implementation A; -(void)a {} @end",
2544                           DefinitionOfObjCMethodA));
2545   EXPECT_TRUE(
2546       notMatchesObjC("@interface A; - (void)a; @end", DefinitionOfObjCMethodA));
2547 }
2548 
TEST_P(ASTMatchersTest,HandlesNullQualTypes)2549 TEST_P(ASTMatchersTest, HandlesNullQualTypes) {
2550   if (!GetParam().isCXX()) {
2551     // FIXME: Add an equivalent test that does not depend on C++.
2552     return;
2553   }
2554 
2555   // FIXME: Add a Type matcher so we can replace uses of this
2556   // variable with Type(True())
2557   const TypeMatcher AnyType = anything();
2558 
2559   // We don't really care whether this matcher succeeds; we're testing that
2560   // it completes without crashing.
2561   EXPECT_TRUE(matches(
2562       "struct A { };"
2563       "template <typename T>"
2564       "void f(T t) {"
2565       "  T local_t(t /* this becomes a null QualType in the AST */);"
2566       "}"
2567       "void g() {"
2568       "  f(0);"
2569       "}",
2570       expr(hasType(TypeMatcher(anyOf(TypeMatcher(hasDeclaration(anything())),
2571                                      pointsTo(AnyType), references(AnyType)
2572                                      // Other QualType matchers should go here.
2573                                      ))))));
2574 }
2575 
TEST_P(ASTMatchersTest,ObjCIvarRefExpr)2576 TEST_P(ASTMatchersTest, ObjCIvarRefExpr) {
2577   StringRef ObjCString =
2578       "@interface A @end "
2579       "@implementation A { A *x; } - (void) func { x = 0; } @end";
2580   EXPECT_TRUE(matchesObjC(ObjCString, objcIvarRefExpr()));
2581   EXPECT_TRUE(matchesObjC(
2582       ObjCString, objcIvarRefExpr(hasDeclaration(namedDecl(hasName("x"))))));
2583   EXPECT_FALSE(matchesObjC(
2584       ObjCString, objcIvarRefExpr(hasDeclaration(namedDecl(hasName("y"))))));
2585 }
2586 
TEST_P(ASTMatchersTest,BlockExpr)2587 TEST_P(ASTMatchersTest, BlockExpr) {
2588   EXPECT_TRUE(matchesObjC("void f() { ^{}(); }", blockExpr()));
2589 }
2590 
TEST_P(ASTMatchersTest,StatementCountIs_FindsNoStatementsInAnEmptyCompoundStatement)2591 TEST_P(ASTMatchersTest,
2592        StatementCountIs_FindsNoStatementsInAnEmptyCompoundStatement) {
2593   EXPECT_TRUE(matches("void f() { }", compoundStmt(statementCountIs(0))));
2594   EXPECT_TRUE(notMatches("void f() {}", compoundStmt(statementCountIs(1))));
2595 }
2596 
TEST_P(ASTMatchersTest,StatementCountIs_AppearsToMatchOnlyOneCount)2597 TEST_P(ASTMatchersTest, StatementCountIs_AppearsToMatchOnlyOneCount) {
2598   EXPECT_TRUE(matches("void f() { 1; }", compoundStmt(statementCountIs(1))));
2599   EXPECT_TRUE(notMatches("void f() { 1; }", compoundStmt(statementCountIs(0))));
2600   EXPECT_TRUE(notMatches("void f() { 1; }", compoundStmt(statementCountIs(2))));
2601 }
2602 
TEST_P(ASTMatchersTest,StatementCountIs_WorksWithMultipleStatements)2603 TEST_P(ASTMatchersTest, StatementCountIs_WorksWithMultipleStatements) {
2604   EXPECT_TRUE(
2605       matches("void f() { 1; 2; 3; }", compoundStmt(statementCountIs(3))));
2606 }
2607 
TEST_P(ASTMatchersTest,StatementCountIs_WorksWithNestedCompoundStatements)2608 TEST_P(ASTMatchersTest, StatementCountIs_WorksWithNestedCompoundStatements) {
2609   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2610                       compoundStmt(statementCountIs(1))));
2611   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2612                       compoundStmt(statementCountIs(2))));
2613   EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
2614                          compoundStmt(statementCountIs(3))));
2615   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2616                       compoundStmt(statementCountIs(4))));
2617 }
2618 
TEST_P(ASTMatchersTest,Member_WorksInSimplestCase)2619 TEST_P(ASTMatchersTest, Member_WorksInSimplestCase) {
2620   if (!GetParam().isCXX()) {
2621     // FIXME: Add a test for `member()` that does not depend on C++.
2622     return;
2623   }
2624   EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
2625                       memberExpr(member(hasName("first")))));
2626 }
2627 
TEST_P(ASTMatchersTest,Member_DoesNotMatchTheBaseExpression)2628 TEST_P(ASTMatchersTest, Member_DoesNotMatchTheBaseExpression) {
2629   if (!GetParam().isCXX()) {
2630     // FIXME: Add a test for `member()` that does not depend on C++.
2631     return;
2632   }
2633 
2634   // Don't pick out the wrong part of the member expression, this should
2635   // be checking the member (name) only.
2636   EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
2637                          memberExpr(member(hasName("first")))));
2638 }
2639 
TEST_P(ASTMatchersTest,Member_MatchesInMemberFunctionCall)2640 TEST_P(ASTMatchersTest, Member_MatchesInMemberFunctionCall) {
2641   if (!GetParam().isCXX()) {
2642     return;
2643   }
2644 
2645   EXPECT_TRUE(matches("void f() {"
2646                       "  struct { void first() {}; } s;"
2647                       "  s.first();"
2648                       "};",
2649                       memberExpr(member(hasName("first")))));
2650 }
2651 
TEST_P(ASTMatchersTest,FieldDecl)2652 TEST_P(ASTMatchersTest, FieldDecl) {
2653   EXPECT_TRUE(
2654       matches("struct A { int i; }; void f() { struct A a; a.i = 2; }",
2655               memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2656   EXPECT_TRUE(
2657       notMatches("struct A { float f; }; void f() { struct A a; a.f = 2.0f; }",
2658                  memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2659 }
2660 
TEST_P(ASTMatchersTest,IsBitField)2661 TEST_P(ASTMatchersTest, IsBitField) {
2662   EXPECT_TRUE(matches("struct C { int a : 2; int b; };",
2663                       fieldDecl(isBitField(), hasName("a"))));
2664   EXPECT_TRUE(notMatches("struct C { int a : 2; int b; };",
2665                          fieldDecl(isBitField(), hasName("b"))));
2666   EXPECT_TRUE(matches("struct C { int a : 2; int b : 4; };",
2667                       fieldDecl(isBitField(), hasBitWidth(2), hasName("a"))));
2668 }
2669 
TEST_P(ASTMatchersTest,HasInClassInitializer)2670 TEST_P(ASTMatchersTest, HasInClassInitializer) {
2671   if (!GetParam().isCXX()) {
2672     return;
2673   }
2674 
2675   EXPECT_TRUE(
2676       matches("class C { int a = 2; int b; };",
2677               fieldDecl(hasInClassInitializer(integerLiteral(equals(2))),
2678                         hasName("a"))));
2679   EXPECT_TRUE(
2680       notMatches("class C { int a = 2; int b; };",
2681                  fieldDecl(hasInClassInitializer(anything()), hasName("b"))));
2682 }
2683 
TEST_P(ASTMatchersTest,IsPublic_IsProtected_IsPrivate)2684 TEST_P(ASTMatchersTest, IsPublic_IsProtected_IsPrivate) {
2685   if (!GetParam().isCXX()) {
2686     return;
2687   }
2688 
2689   EXPECT_TRUE(
2690       matches("struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2691   EXPECT_TRUE(notMatches("struct A { int i; };",
2692                          fieldDecl(isProtected(), hasName("i"))));
2693   EXPECT_TRUE(
2694       notMatches("struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2695 
2696   EXPECT_TRUE(
2697       notMatches("class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2698   EXPECT_TRUE(notMatches("class A { int i; };",
2699                          fieldDecl(isProtected(), hasName("i"))));
2700   EXPECT_TRUE(
2701       matches("class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2702 
2703   EXPECT_TRUE(notMatches("class A { protected: int i; };",
2704                          fieldDecl(isPublic(), hasName("i"))));
2705   EXPECT_TRUE(matches("class A { protected: int i; };",
2706                       fieldDecl(isProtected(), hasName("i"))));
2707   EXPECT_TRUE(notMatches("class A { protected: int i; };",
2708                          fieldDecl(isPrivate(), hasName("i"))));
2709 
2710   // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2711   EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2712   EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2713   EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2714 }
2715 
TEST_P(ASTMatchersTest,HasDynamicExceptionSpec_MatchesDynamicExceptionSpecifications)2716 TEST_P(ASTMatchersTest,
2717        HasDynamicExceptionSpec_MatchesDynamicExceptionSpecifications) {
2718   if (!GetParam().supportsCXXDynamicExceptionSpecification()) {
2719     return;
2720   }
2721 
2722   EXPECT_TRUE(notMatches("void f();", functionDecl(hasDynamicExceptionSpec())));
2723   EXPECT_TRUE(
2724       matches("void j() throw();", functionDecl(hasDynamicExceptionSpec())));
2725   EXPECT_TRUE(
2726       matches("void k() throw(int);", functionDecl(hasDynamicExceptionSpec())));
2727   EXPECT_TRUE(
2728       matches("void l() throw(...);", functionDecl(hasDynamicExceptionSpec())));
2729 
2730   EXPECT_TRUE(
2731       notMatches("void f();", functionProtoType(hasDynamicExceptionSpec())));
2732   EXPECT_TRUE(matches("void j() throw();",
2733                       functionProtoType(hasDynamicExceptionSpec())));
2734   EXPECT_TRUE(matches("void k() throw(int);",
2735                       functionProtoType(hasDynamicExceptionSpec())));
2736   EXPECT_TRUE(matches("void l() throw(...);",
2737                       functionProtoType(hasDynamicExceptionSpec())));
2738 }
2739 
TEST_P(ASTMatchersTest,HasDynamicExceptionSpec_MatchesDynamicExceptionSpecifications_CXX11)2740 TEST_P(ASTMatchersTest,
2741        HasDynamicExceptionSpec_MatchesDynamicExceptionSpecifications_CXX11) {
2742   if (!GetParam().isCXX11OrLater()) {
2743     return;
2744   }
2745 
2746   EXPECT_TRUE(notMatches("void g() noexcept;",
2747                          functionDecl(hasDynamicExceptionSpec())));
2748   EXPECT_TRUE(notMatches("void h() noexcept(true);",
2749                          functionDecl(hasDynamicExceptionSpec())));
2750   EXPECT_TRUE(notMatches("void i() noexcept(false);",
2751                          functionDecl(hasDynamicExceptionSpec())));
2752 
2753   EXPECT_TRUE(notMatches("void g() noexcept;",
2754                          functionProtoType(hasDynamicExceptionSpec())));
2755   EXPECT_TRUE(notMatches("void h() noexcept(true);",
2756                          functionProtoType(hasDynamicExceptionSpec())));
2757   EXPECT_TRUE(notMatches("void i() noexcept(false);",
2758                          functionProtoType(hasDynamicExceptionSpec())));
2759 }
2760 
TEST_P(ASTMatchersTest,HasObjectExpression_DoesNotMatchMember)2761 TEST_P(ASTMatchersTest, HasObjectExpression_DoesNotMatchMember) {
2762   if (!GetParam().isCXX()) {
2763     return;
2764   }
2765 
2766   EXPECT_TRUE(notMatches(
2767       "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
2768       memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
2769 }
2770 
TEST_P(ASTMatchersTest,HasObjectExpression_MatchesBaseOfVariable)2771 TEST_P(ASTMatchersTest, HasObjectExpression_MatchesBaseOfVariable) {
2772   EXPECT_TRUE(matches(
2773       "struct X { int m; }; void f(struct X x) { x.m; }",
2774       memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
2775   EXPECT_TRUE(matches("struct X { int m; }; void f(struct X* x) { x->m; }",
2776                       memberExpr(hasObjectExpression(
2777                           hasType(pointsTo(recordDecl(hasName("X"))))))));
2778 }
2779 
TEST_P(ASTMatchersTest,HasObjectExpression_MatchesBaseOfVariable_CXX)2780 TEST_P(ASTMatchersTest, HasObjectExpression_MatchesBaseOfVariable_CXX) {
2781   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
2782     // FIXME: Fix this test to work with delayed template parsing.
2783     return;
2784   }
2785 
2786   EXPECT_TRUE(matches("template <class T> struct X { void f() { T t; t.m; } };",
2787                       cxxDependentScopeMemberExpr(hasObjectExpression(
2788                           declRefExpr(to(namedDecl(hasName("t"))))))));
2789   EXPECT_TRUE(
2790       matches("template <class T> struct X { void f() { T t; t->m; } };",
2791               cxxDependentScopeMemberExpr(hasObjectExpression(
2792                   declRefExpr(to(namedDecl(hasName("t"))))))));
2793 }
2794 
TEST_P(ASTMatchersTest,HasObjectExpression_MatchesBaseOfMemberFunc)2795 TEST_P(ASTMatchersTest, HasObjectExpression_MatchesBaseOfMemberFunc) {
2796   if (!GetParam().isCXX()) {
2797     return;
2798   }
2799 
2800   EXPECT_TRUE(matches(
2801       "struct X { void f(); }; void g(X x) { x.f(); }",
2802       memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
2803 }
2804 
TEST_P(ASTMatchersTest,HasObjectExpression_MatchesBaseOfMemberFunc_Template)2805 TEST_P(ASTMatchersTest, HasObjectExpression_MatchesBaseOfMemberFunc_Template) {
2806   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
2807     // FIXME: Fix this test to work with delayed template parsing.
2808     return;
2809   }
2810 
2811   EXPECT_TRUE(matches("struct X { template <class T> void f(); };"
2812                       "template <class T> void g(X x) { x.f<T>(); }",
2813                       unresolvedMemberExpr(hasObjectExpression(
2814                           hasType(recordDecl(hasName("X")))))));
2815   EXPECT_TRUE(matches("template <class T> void f(T t) { t.g(); }",
2816                       cxxDependentScopeMemberExpr(hasObjectExpression(
2817                           declRefExpr(to(namedDecl(hasName("t"))))))));
2818 }
2819 
TEST_P(ASTMatchersTest,HasObjectExpression_ImplicitlyFormedMemberExpression)2820 TEST_P(ASTMatchersTest, HasObjectExpression_ImplicitlyFormedMemberExpression) {
2821   if (!GetParam().isCXX()) {
2822     return;
2823   }
2824 
2825   EXPECT_TRUE(matches("class X {}; struct S { X m; void f() { this->m; } };",
2826                       memberExpr(hasObjectExpression(
2827                           hasType(pointsTo(recordDecl(hasName("S"))))))));
2828   EXPECT_TRUE(matches("class X {}; struct S { X m; void f() { m; } };",
2829                       memberExpr(hasObjectExpression(
2830                           hasType(pointsTo(recordDecl(hasName("S"))))))));
2831 }
2832 
TEST_P(ASTMatchersTest,FieldDecl_DoesNotMatchNonFieldMembers)2833 TEST_P(ASTMatchersTest, FieldDecl_DoesNotMatchNonFieldMembers) {
2834   if (!GetParam().isCXX()) {
2835     return;
2836   }
2837 
2838   EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2839   EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2840   EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2841   EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
2842 }
2843 
TEST_P(ASTMatchersTest,FieldDecl_MatchesField)2844 TEST_P(ASTMatchersTest, FieldDecl_MatchesField) {
2845   EXPECT_TRUE(matches("struct X { int m; };", fieldDecl(hasName("m"))));
2846 }
2847 
TEST_P(ASTMatchersTest,IsVolatileQualified)2848 TEST_P(ASTMatchersTest, IsVolatileQualified) {
2849   EXPECT_TRUE(
2850       matches("volatile int i = 42;", varDecl(hasType(isVolatileQualified()))));
2851   EXPECT_TRUE(
2852       notMatches("volatile int *i;", varDecl(hasType(isVolatileQualified()))));
2853   EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
2854                       varDecl(hasType(isVolatileQualified()))));
2855 }
2856 
TEST_P(ASTMatchersTest,IsConstQualified_MatchesConstInt)2857 TEST_P(ASTMatchersTest, IsConstQualified_MatchesConstInt) {
2858   EXPECT_TRUE(
2859       matches("const int i = 42;", varDecl(hasType(isConstQualified()))));
2860 }
2861 
TEST_P(ASTMatchersTest,IsConstQualified_MatchesConstPointer)2862 TEST_P(ASTMatchersTest, IsConstQualified_MatchesConstPointer) {
2863   EXPECT_TRUE(matches("int i = 42; int* const p = &i;",
2864                       varDecl(hasType(isConstQualified()))));
2865 }
2866 
TEST_P(ASTMatchersTest,IsConstQualified_MatchesThroughTypedef)2867 TEST_P(ASTMatchersTest, IsConstQualified_MatchesThroughTypedef) {
2868   EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
2869                       varDecl(hasType(isConstQualified()))));
2870   EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p = ((int*)0);",
2871                       varDecl(hasType(isConstQualified()))));
2872 }
2873 
TEST_P(ASTMatchersTest,IsConstQualified_DoesNotMatchInappropriately)2874 TEST_P(ASTMatchersTest, IsConstQualified_DoesNotMatchInappropriately) {
2875   EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
2876                          varDecl(hasType(isConstQualified()))));
2877   EXPECT_TRUE(
2878       notMatches("int const* p;", varDecl(hasType(isConstQualified()))));
2879 }
2880 
TEST_P(ASTMatchersTest,DeclCountIs_DeclCountIsCorrect)2881 TEST_P(ASTMatchersTest, DeclCountIs_DeclCountIsCorrect) {
2882   EXPECT_TRUE(matches("void f() {int i,j;}", declStmt(declCountIs(2))));
2883   EXPECT_TRUE(
2884       notMatches("void f() {int i,j; int k;}", declStmt(declCountIs(3))));
2885   EXPECT_TRUE(
2886       notMatches("void f() {int i,j, k, l;}", declStmt(declCountIs(3))));
2887 }
2888 
TEST_P(ASTMatchersTest,EachOf_TriggersForEachMatch)2889 TEST_P(ASTMatchersTest, EachOf_TriggersForEachMatch) {
2890   EXPECT_TRUE(matchAndVerifyResultTrue(
2891       "class A { int a; int b; };",
2892       recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2893                         has(fieldDecl(hasName("b")).bind("v")))),
2894       std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 2)));
2895 }
2896 
TEST_P(ASTMatchersTest,EachOf_BehavesLikeAnyOfUnlessBothMatch)2897 TEST_P(ASTMatchersTest, EachOf_BehavesLikeAnyOfUnlessBothMatch) {
2898   EXPECT_TRUE(matchAndVerifyResultTrue(
2899       "struct A { int a; int c; };",
2900       recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2901                         has(fieldDecl(hasName("b")).bind("v")))),
2902       std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
2903   EXPECT_TRUE(matchAndVerifyResultTrue(
2904       "struct A { int c; int b; };",
2905       recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2906                         has(fieldDecl(hasName("b")).bind("v")))),
2907       std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
2908   EXPECT_TRUE(
2909       notMatches("struct A { int c; int d; };",
2910                  recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2911                                    has(fieldDecl(hasName("b")).bind("v"))))));
2912 }
2913 
TEST_P(ASTMatchersTest,Optionally_SubmatchersDoNotMatch)2914 TEST_P(ASTMatchersTest, Optionally_SubmatchersDoNotMatch) {
2915   EXPECT_TRUE(matchAndVerifyResultFalse(
2916       "class A { int a; int b; };",
2917       recordDecl(optionally(has(fieldDecl(hasName("c")).bind("c")))),
2918       std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("c")));
2919 }
2920 
2921 // Regression test.
TEST_P(ASTMatchersTest,Optionally_SubmatchersDoNotMatchButPreserveBindings)2922 TEST_P(ASTMatchersTest, Optionally_SubmatchersDoNotMatchButPreserveBindings) {
2923   StringRef Code = "class A { int a; int b; };";
2924   auto Matcher = recordDecl(decl().bind("decl"),
2925                             optionally(has(fieldDecl(hasName("c")).bind("v"))));
2926   // "decl" is still bound.
2927   EXPECT_TRUE(matchAndVerifyResultTrue(
2928       Code, Matcher, std::make_unique<VerifyIdIsBoundTo<RecordDecl>>("decl")));
2929   // "v" is not bound, but the match still suceeded.
2930   EXPECT_TRUE(matchAndVerifyResultFalse(
2931       Code, Matcher, std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v")));
2932 }
2933 
TEST_P(ASTMatchersTest,Optionally_SubmatchersMatch)2934 TEST_P(ASTMatchersTest, Optionally_SubmatchersMatch) {
2935   EXPECT_TRUE(matchAndVerifyResultTrue(
2936       "class A { int a; int c; };",
2937       recordDecl(optionally(has(fieldDecl(hasName("a")).bind("v")))),
2938       std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v")));
2939 }
2940 
TEST_P(ASTMatchersTest,IsTemplateInstantiation_MatchesImplicitClassTemplateInstantiation)2941 TEST_P(ASTMatchersTest,
2942        IsTemplateInstantiation_MatchesImplicitClassTemplateInstantiation) {
2943   if (!GetParam().isCXX()) {
2944     return;
2945   }
2946 
2947   // Make sure that we can both match the class by name (::X) and by the type
2948   // the template was instantiated with (via a field).
2949 
2950   EXPECT_TRUE(
2951       matches("template <typename T> class X {}; class A {}; X<A> x;",
2952               cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
2953 
2954   EXPECT_TRUE(matches(
2955       "template <typename T> class X { T t; }; class A {}; X<A> x;",
2956       cxxRecordDecl(
2957           isTemplateInstantiation(),
2958           hasDescendant(fieldDecl(hasType(recordDecl(hasName("A"))))))));
2959 }
2960 
TEST_P(ASTMatchersTest,IsTemplateInstantiation_MatchesImplicitFunctionTemplateInstantiation)2961 TEST_P(ASTMatchersTest,
2962        IsTemplateInstantiation_MatchesImplicitFunctionTemplateInstantiation) {
2963   if (!GetParam().isCXX()) {
2964     return;
2965   }
2966 
2967   EXPECT_TRUE(matches(
2968       "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
2969       functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
2970                    isTemplateInstantiation())));
2971 }
2972 
TEST_P(ASTMatchersTest,IsTemplateInstantiation_MatchesExplicitClassTemplateInstantiation)2973 TEST_P(ASTMatchersTest,
2974        IsTemplateInstantiation_MatchesExplicitClassTemplateInstantiation) {
2975   if (!GetParam().isCXX()) {
2976     return;
2977   }
2978 
2979   EXPECT_TRUE(matches("template <typename T> class X { T t; }; class A {};"
2980                       "template class X<A>;",
2981                       cxxRecordDecl(isTemplateInstantiation(),
2982                                     hasDescendant(fieldDecl(
2983                                         hasType(recordDecl(hasName("A"))))))));
2984 
2985   // Make sure that we match the instantiation instead of the template
2986   // definition by checking whether the member function is present.
2987   EXPECT_TRUE(
2988       matches("template <typename T> class X { void f() { T t; } };"
2989               "extern template class X<int>;",
2990               cxxRecordDecl(isTemplateInstantiation(),
2991                             unless(hasDescendant(varDecl(hasName("t")))))));
2992 }
2993 
TEST_P(ASTMatchersTest,IsTemplateInstantiation_MatchesInstantiationOfPartiallySpecializedClassTemplate)2994 TEST_P(
2995     ASTMatchersTest,
2996     IsTemplateInstantiation_MatchesInstantiationOfPartiallySpecializedClassTemplate) {
2997   if (!GetParam().isCXX()) {
2998     return;
2999   }
3000 
3001   EXPECT_TRUE(
3002       matches("template <typename T> class X {};"
3003               "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
3004               cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
3005 }
3006 
TEST_P(ASTMatchersTest,IsTemplateInstantiation_MatchesInstantiationOfClassTemplateNestedInNonTemplate)3007 TEST_P(
3008     ASTMatchersTest,
3009     IsTemplateInstantiation_MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3010   if (!GetParam().isCXX()) {
3011     return;
3012   }
3013 
3014   EXPECT_TRUE(
3015       matches("class A {};"
3016               "class X {"
3017               "  template <typename U> class Y { U u; };"
3018               "  Y<A> y;"
3019               "};",
3020               cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
3021 }
3022 
TEST_P(ASTMatchersTest,IsTemplateInstantiation_DoesNotMatchInstantiationsInsideOfInstantiation)3023 TEST_P(
3024     ASTMatchersTest,
3025     IsTemplateInstantiation_DoesNotMatchInstantiationsInsideOfInstantiation) {
3026   if (!GetParam().isCXX()) {
3027     return;
3028   }
3029 
3030   // FIXME: Figure out whether this makes sense. It doesn't affect the
3031   // normal use case as long as the uppermost instantiation always is marked
3032   // as template instantiation, but it might be confusing as a predicate.
3033   EXPECT_TRUE(matches(
3034       "class A {};"
3035       "template <typename T> class X {"
3036       "  template <typename U> class Y { U u; };"
3037       "  Y<T> y;"
3038       "}; X<A> x;",
3039       cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
3040 }
3041 
TEST_P(ASTMatchersTest,IsTemplateInstantiation_DoesNotMatchExplicitClassTemplateSpecialization)3042 TEST_P(
3043     ASTMatchersTest,
3044     IsTemplateInstantiation_DoesNotMatchExplicitClassTemplateSpecialization) {
3045   if (!GetParam().isCXX()) {
3046     return;
3047   }
3048 
3049   EXPECT_TRUE(
3050       notMatches("template <typename T> class X {}; class A {};"
3051                  "template <> class X<A> {}; X<A> x;",
3052                  cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
3053 }
3054 
TEST_P(ASTMatchersTest,IsTemplateInstantiation_DoesNotMatchNonTemplate)3055 TEST_P(ASTMatchersTest, IsTemplateInstantiation_DoesNotMatchNonTemplate) {
3056   if (!GetParam().isCXX()) {
3057     return;
3058   }
3059 
3060   EXPECT_TRUE(notMatches("class A {}; class Y { A a; };",
3061                          cxxRecordDecl(isTemplateInstantiation())));
3062 }
3063 
TEST_P(ASTMatchersTest,IsInstantiated_MatchesInstantiation)3064 TEST_P(ASTMatchersTest, IsInstantiated_MatchesInstantiation) {
3065   if (!GetParam().isCXX()) {
3066     return;
3067   }
3068 
3069   EXPECT_TRUE(
3070       matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3071               cxxRecordDecl(isInstantiated())));
3072 }
3073 
TEST_P(ASTMatchersTest,IsInstantiated_NotMatchesDefinition)3074 TEST_P(ASTMatchersTest, IsInstantiated_NotMatchesDefinition) {
3075   if (!GetParam().isCXX()) {
3076     return;
3077   }
3078 
3079   EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3080                          cxxRecordDecl(isInstantiated())));
3081 }
3082 
TEST_P(ASTMatchersTest,IsInTemplateInstantiation_MatchesInstantiationStmt)3083 TEST_P(ASTMatchersTest, IsInTemplateInstantiation_MatchesInstantiationStmt) {
3084   if (!GetParam().isCXX()) {
3085     return;
3086   }
3087 
3088   EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3089                       "class Y { A<int> a; }; Y y;",
3090                       declStmt(isInTemplateInstantiation())));
3091 }
3092 
TEST_P(ASTMatchersTest,IsInTemplateInstantiation_NotMatchesDefinitionStmt)3093 TEST_P(ASTMatchersTest, IsInTemplateInstantiation_NotMatchesDefinitionStmt) {
3094   if (!GetParam().isCXX()) {
3095     return;
3096   }
3097 
3098   EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3099                          declStmt(isInTemplateInstantiation())));
3100 }
3101 
TEST_P(ASTMatchersTest,IsInstantiated_MatchesFunctionInstantiation)3102 TEST_P(ASTMatchersTest, IsInstantiated_MatchesFunctionInstantiation) {
3103   if (!GetParam().isCXX()) {
3104     return;
3105   }
3106 
3107   EXPECT_TRUE(
3108       matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3109               functionDecl(isInstantiated())));
3110 }
3111 
TEST_P(ASTMatchersTest,IsInstantiated_NotMatchesFunctionDefinition)3112 TEST_P(ASTMatchersTest, IsInstantiated_NotMatchesFunctionDefinition) {
3113   if (!GetParam().isCXX()) {
3114     return;
3115   }
3116 
3117   EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3118                          varDecl(isInstantiated())));
3119 }
3120 
TEST_P(ASTMatchersTest,IsInTemplateInstantiation_MatchesFunctionInstantiationStmt)3121 TEST_P(ASTMatchersTest,
3122        IsInTemplateInstantiation_MatchesFunctionInstantiationStmt) {
3123   if (!GetParam().isCXX()) {
3124     return;
3125   }
3126 
3127   EXPECT_TRUE(
3128       matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3129               declStmt(isInTemplateInstantiation())));
3130 }
3131 
TEST_P(ASTMatchersTest,IsInTemplateInstantiation_NotMatchesFunctionDefinitionStmt)3132 TEST_P(ASTMatchersTest,
3133        IsInTemplateInstantiation_NotMatchesFunctionDefinitionStmt) {
3134   if (!GetParam().isCXX()) {
3135     return;
3136   }
3137 
3138   EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3139                          declStmt(isInTemplateInstantiation())));
3140 }
3141 
TEST_P(ASTMatchersTest,IsInTemplateInstantiation_Sharing)3142 TEST_P(ASTMatchersTest, IsInTemplateInstantiation_Sharing) {
3143   if (!GetParam().isCXX()) {
3144     return;
3145   }
3146 
3147   auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3148   // FIXME: Node sharing is an implementation detail, exposing it is ugly
3149   // and makes the matcher behave in non-obvious ways.
3150   EXPECT_TRUE(notMatches(
3151       "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3152       Matcher));
3153   EXPECT_TRUE(matches(
3154       "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3155       Matcher));
3156 }
3157 
TEST_P(ASTMatchersTest,IsInstantiationDependent_MatchesNonValueTypeDependent)3158 TEST_P(ASTMatchersTest, IsInstantiationDependent_MatchesNonValueTypeDependent) {
3159   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3160     // FIXME: Fix this test to work with delayed template parsing.
3161     return;
3162   }
3163 
3164   EXPECT_TRUE(matches(
3165       "template<typename T> void f() { (void) sizeof(sizeof(T() + T())); }",
3166       expr(isInstantiationDependent())));
3167 }
3168 
TEST_P(ASTMatchersTest,IsInstantiationDependent_MatchesValueDependent)3169 TEST_P(ASTMatchersTest, IsInstantiationDependent_MatchesValueDependent) {
3170   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3171     // FIXME: Fix this test to work with delayed template parsing.
3172     return;
3173   }
3174 
3175   EXPECT_TRUE(matches("template<int T> int f() { return T; }",
3176                       expr(isInstantiationDependent())));
3177 }
3178 
TEST_P(ASTMatchersTest,IsInstantiationDependent_MatchesTypeDependent)3179 TEST_P(ASTMatchersTest, IsInstantiationDependent_MatchesTypeDependent) {
3180   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3181     // FIXME: Fix this test to work with delayed template parsing.
3182     return;
3183   }
3184 
3185   EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
3186                       expr(isInstantiationDependent())));
3187 }
3188 
TEST_P(ASTMatchersTest,IsTypeDependent_MatchesTypeDependent)3189 TEST_P(ASTMatchersTest, IsTypeDependent_MatchesTypeDependent) {
3190   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3191     // FIXME: Fix this test to work with delayed template parsing.
3192     return;
3193   }
3194 
3195   EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
3196                       expr(isTypeDependent())));
3197 }
3198 
TEST_P(ASTMatchersTest,IsTypeDependent_NotMatchesValueDependent)3199 TEST_P(ASTMatchersTest, IsTypeDependent_NotMatchesValueDependent) {
3200   if (!GetParam().isCXX()) {
3201     return;
3202   }
3203 
3204   EXPECT_TRUE(notMatches("template<int T> int f() { return T; }",
3205                          expr(isTypeDependent())));
3206 }
3207 
TEST_P(ASTMatchersTest,IsValueDependent_MatchesValueDependent)3208 TEST_P(ASTMatchersTest, IsValueDependent_MatchesValueDependent) {
3209   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3210     // FIXME: Fix this test to work with delayed template parsing.
3211     return;
3212   }
3213 
3214   EXPECT_TRUE(matches("template<int T> int f() { return T; }",
3215                       expr(isValueDependent())));
3216 }
3217 
TEST_P(ASTMatchersTest,IsValueDependent_MatchesTypeDependent)3218 TEST_P(ASTMatchersTest, IsValueDependent_MatchesTypeDependent) {
3219   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3220     // FIXME: Fix this test to work with delayed template parsing.
3221     return;
3222   }
3223 
3224   EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
3225                       expr(isValueDependent())));
3226 }
3227 
TEST_P(ASTMatchersTest,IsValueDependent_MatchesInstantiationDependent)3228 TEST_P(ASTMatchersTest, IsValueDependent_MatchesInstantiationDependent) {
3229   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3230     // FIXME: Fix this test to work with delayed template parsing.
3231     return;
3232   }
3233 
3234   EXPECT_TRUE(matches(
3235       "template<typename T> void f() { (void) sizeof(sizeof(T() + T())); }",
3236       expr(isValueDependent())));
3237 }
3238 
TEST_P(ASTMatchersTest,IsExplicitTemplateSpecialization_DoesNotMatchPrimaryTemplate)3239 TEST_P(ASTMatchersTest,
3240        IsExplicitTemplateSpecialization_DoesNotMatchPrimaryTemplate) {
3241   if (!GetParam().isCXX()) {
3242     return;
3243   }
3244 
3245   EXPECT_TRUE(notMatches("template <typename T> class X {};",
3246                          cxxRecordDecl(isExplicitTemplateSpecialization())));
3247   EXPECT_TRUE(notMatches("template <typename T> void f(T t);",
3248                          functionDecl(isExplicitTemplateSpecialization())));
3249 }
3250 
TEST_P(ASTMatchersTest,IsExplicitTemplateSpecialization_DoesNotMatchExplicitTemplateInstantiations)3251 TEST_P(
3252     ASTMatchersTest,
3253     IsExplicitTemplateSpecialization_DoesNotMatchExplicitTemplateInstantiations) {
3254   if (!GetParam().isCXX()) {
3255     return;
3256   }
3257 
3258   EXPECT_TRUE(
3259       notMatches("template <typename T> class X {};"
3260                  "template class X<int>; extern template class X<long>;",
3261                  cxxRecordDecl(isExplicitTemplateSpecialization())));
3262   EXPECT_TRUE(
3263       notMatches("template <typename T> void f(T t) {}"
3264                  "template void f(int t); extern template void f(long t);",
3265                  functionDecl(isExplicitTemplateSpecialization())));
3266 }
3267 
TEST_P(ASTMatchersTest,IsExplicitTemplateSpecialization_DoesNotMatchImplicitTemplateInstantiations)3268 TEST_P(
3269     ASTMatchersTest,
3270     IsExplicitTemplateSpecialization_DoesNotMatchImplicitTemplateInstantiations) {
3271   if (!GetParam().isCXX()) {
3272     return;
3273   }
3274 
3275   EXPECT_TRUE(notMatches("template <typename T> class X {}; X<int> x;",
3276                          cxxRecordDecl(isExplicitTemplateSpecialization())));
3277   EXPECT_TRUE(
3278       notMatches("template <typename T> void f(T t); void g() { f(10); }",
3279                  functionDecl(isExplicitTemplateSpecialization())));
3280 }
3281 
TEST_P(ASTMatchersTest,IsExplicitTemplateSpecialization_MatchesExplicitTemplateSpecializations)3282 TEST_P(
3283     ASTMatchersTest,
3284     IsExplicitTemplateSpecialization_MatchesExplicitTemplateSpecializations) {
3285   if (!GetParam().isCXX()) {
3286     return;
3287   }
3288 
3289   EXPECT_TRUE(matches("template <typename T> class X {};"
3290                       "template<> class X<int> {};",
3291                       cxxRecordDecl(isExplicitTemplateSpecialization())));
3292   EXPECT_TRUE(matches("template <typename T> void f(T t) {}"
3293                       "template<> void f(int t) {}",
3294                       functionDecl(isExplicitTemplateSpecialization())));
3295 }
3296 
TEST_P(ASTMatchersTest,IsNoReturn)3297 TEST_P(ASTMatchersTest, IsNoReturn) {
3298   EXPECT_TRUE(notMatches("void func();", functionDecl(isNoReturn())));
3299   EXPECT_TRUE(notMatches("void func() {}", functionDecl(isNoReturn())));
3300 
3301   EXPECT_TRUE(matches("__attribute__((noreturn)) void func();",
3302                       functionDecl(isNoReturn())));
3303   EXPECT_TRUE(matches("__attribute__((noreturn)) void func() {}",
3304                       functionDecl(isNoReturn())));
3305 
3306   EXPECT_TRUE(matches("_Noreturn void func();", functionDecl(isNoReturn())));
3307   EXPECT_TRUE(matches("_Noreturn void func() {}", functionDecl(isNoReturn())));
3308 }
3309 
TEST_P(ASTMatchersTest,IsNoReturn_CXX)3310 TEST_P(ASTMatchersTest, IsNoReturn_CXX) {
3311   if (!GetParam().isCXX()) {
3312     return;
3313   }
3314 
3315   EXPECT_TRUE(
3316       notMatches("struct S { void func(); };", functionDecl(isNoReturn())));
3317   EXPECT_TRUE(
3318       notMatches("struct S { void func() {} };", functionDecl(isNoReturn())));
3319 
3320   EXPECT_TRUE(notMatches("struct S { static void func(); };",
3321                          functionDecl(isNoReturn())));
3322   EXPECT_TRUE(notMatches("struct S { static void func() {} };",
3323                          functionDecl(isNoReturn())));
3324 
3325   EXPECT_TRUE(notMatches("struct S { S(); };", functionDecl(isNoReturn())));
3326   EXPECT_TRUE(notMatches("struct S { S() {} };", functionDecl(isNoReturn())));
3327 
3328   // ---
3329 
3330   EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) void func(); };",
3331                       functionDecl(isNoReturn())));
3332   EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) void func() {} };",
3333                       functionDecl(isNoReturn())));
3334 
3335   EXPECT_TRUE(
3336       matches("struct S { __attribute__((noreturn)) static void func(); };",
3337               functionDecl(isNoReturn())));
3338   EXPECT_TRUE(
3339       matches("struct S { __attribute__((noreturn)) static void func() {} };",
3340               functionDecl(isNoReturn())));
3341 
3342   EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) S(); };",
3343                       functionDecl(isNoReturn())));
3344   EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) S() {} };",
3345                       functionDecl(isNoReturn())));
3346 }
3347 
TEST_P(ASTMatchersTest,IsNoReturn_CXX11Attribute)3348 TEST_P(ASTMatchersTest, IsNoReturn_CXX11Attribute) {
3349   if (!GetParam().isCXX11OrLater()) {
3350     return;
3351   }
3352 
3353   EXPECT_TRUE(matches("[[noreturn]] void func();", functionDecl(isNoReturn())));
3354   EXPECT_TRUE(
3355       matches("[[noreturn]] void func() {}", functionDecl(isNoReturn())));
3356 
3357   EXPECT_TRUE(matches("struct S { [[noreturn]] void func(); };",
3358                       functionDecl(isNoReturn())));
3359   EXPECT_TRUE(matches("struct S { [[noreturn]] void func() {} };",
3360                       functionDecl(isNoReturn())));
3361 
3362   EXPECT_TRUE(matches("struct S { [[noreturn]] static void func(); };",
3363                       functionDecl(isNoReturn())));
3364   EXPECT_TRUE(matches("struct S { [[noreturn]] static void func() {} };",
3365                       functionDecl(isNoReturn())));
3366 
3367   EXPECT_TRUE(
3368       matches("struct S { [[noreturn]] S(); };", functionDecl(isNoReturn())));
3369   EXPECT_TRUE(
3370       matches("struct S { [[noreturn]] S() {} };", functionDecl(isNoReturn())));
3371 }
3372 
TEST_P(ASTMatchersTest,BooleanType)3373 TEST_P(ASTMatchersTest, BooleanType) {
3374   if (!GetParam().isCXX()) {
3375     // FIXME: Add a test for `booleanType()` that does not depend on C++.
3376     return;
3377   }
3378 
3379   EXPECT_TRUE(matches("struct S { bool func(); };",
3380                       cxxMethodDecl(returns(booleanType()))));
3381   EXPECT_TRUE(notMatches("struct S { void func(); };",
3382                          cxxMethodDecl(returns(booleanType()))));
3383 }
3384 
TEST_P(ASTMatchersTest,VoidType)3385 TEST_P(ASTMatchersTest, VoidType) {
3386   if (!GetParam().isCXX()) {
3387     // FIXME: Add a test for `voidType()` that does not depend on C++.
3388     return;
3389   }
3390 
3391   EXPECT_TRUE(matches("struct S { void func(); };",
3392                       cxxMethodDecl(returns(voidType()))));
3393 }
3394 
TEST_P(ASTMatchersTest,RealFloatingPointType)3395 TEST_P(ASTMatchersTest, RealFloatingPointType) {
3396   if (!GetParam().isCXX()) {
3397     // FIXME: Add a test for `realFloatingPointType()` that does not depend on
3398     // C++.
3399     return;
3400   }
3401 
3402   EXPECT_TRUE(matches("struct S { float func(); };",
3403                       cxxMethodDecl(returns(realFloatingPointType()))));
3404   EXPECT_TRUE(notMatches("struct S { int func(); };",
3405                          cxxMethodDecl(returns(realFloatingPointType()))));
3406   EXPECT_TRUE(matches("struct S { long double func(); };",
3407                       cxxMethodDecl(returns(realFloatingPointType()))));
3408 }
3409 
TEST_P(ASTMatchersTest,ArrayType)3410 TEST_P(ASTMatchersTest, ArrayType) {
3411   EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3412   EXPECT_TRUE(matches("int a[42];", arrayType()));
3413   EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3414 
3415   EXPECT_TRUE(notMatches("struct A {}; struct A a[7];",
3416                          arrayType(hasElementType(builtinType()))));
3417 
3418   EXPECT_TRUE(matches("int const a[] = { 2, 3 };",
3419                       qualType(arrayType(hasElementType(builtinType())))));
3420   EXPECT_TRUE(matches(
3421       "int const a[] = { 2, 3 };",
3422       qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3423   EXPECT_TRUE(matches("typedef const int T; T x[] = { 1, 2 };",
3424                       qualType(isConstQualified(), arrayType())));
3425 
3426   EXPECT_TRUE(notMatches(
3427       "int a[] = { 2, 3 };",
3428       qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3429   EXPECT_TRUE(notMatches(
3430       "int a[] = { 2, 3 };",
3431       qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3432   EXPECT_TRUE(notMatches("int const a[] = { 2, 3 };",
3433                          qualType(arrayType(hasElementType(builtinType())),
3434                                   unless(isConstQualified()))));
3435 
3436   EXPECT_TRUE(
3437       matches("int a[2];", constantArrayType(hasElementType(builtinType()))));
3438   EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3439 }
3440 
TEST_P(ASTMatchersTest,DecayedType)3441 TEST_P(ASTMatchersTest, DecayedType) {
3442   EXPECT_TRUE(
3443       matches("void f(int i[]);",
3444               valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
3445   EXPECT_TRUE(notMatches("int i[7];", decayedType()));
3446 }
3447 
TEST_P(ASTMatchersTest,ComplexType)3448 TEST_P(ASTMatchersTest, ComplexType) {
3449   EXPECT_TRUE(matches("_Complex float f;", complexType()));
3450   EXPECT_TRUE(
3451       matches("_Complex float f;", complexType(hasElementType(builtinType()))));
3452   EXPECT_TRUE(notMatches("_Complex float f;",
3453                          complexType(hasElementType(isInteger()))));
3454 }
3455 
TEST_P(ASTMatchersTest,IsAnonymous)3456 TEST_P(ASTMatchersTest, IsAnonymous) {
3457   if (!GetParam().isCXX()) {
3458     return;
3459   }
3460 
3461   EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
3462   EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
3463 }
3464 
TEST_P(ASTMatchersTest,InStdNamespace)3465 TEST_P(ASTMatchersTest, InStdNamespace) {
3466   if (!GetParam().isCXX()) {
3467     return;
3468   }
3469 
3470   EXPECT_TRUE(notMatches("class vector {};"
3471                          "namespace foo {"
3472                          "  class vector {};"
3473                          "}"
3474                          "namespace foo {"
3475                          "  namespace std {"
3476                          "    class vector {};"
3477                          "  }"
3478                          "}",
3479                          cxxRecordDecl(hasName("vector"), isInStdNamespace())));
3480 
3481   EXPECT_TRUE(matches("namespace std {"
3482                       "  class vector {};"
3483                       "}",
3484                       cxxRecordDecl(hasName("vector"), isInStdNamespace())));
3485 }
3486 
TEST_P(ASTMatchersTest,InStdNamespace_CXX11)3487 TEST_P(ASTMatchersTest, InStdNamespace_CXX11) {
3488   if (!GetParam().isCXX11OrLater()) {
3489     return;
3490   }
3491 
3492   EXPECT_TRUE(matches("namespace std {"
3493                       "  inline namespace __1 {"
3494                       "    class vector {};"
3495                       "  }"
3496                       "}",
3497                       cxxRecordDecl(hasName("vector"), isInStdNamespace())));
3498   EXPECT_TRUE(notMatches("namespace std {"
3499                          "  inline namespace __1 {"
3500                          "    inline namespace __fs {"
3501                          "      namespace filesystem {"
3502                          "        inline namespace v1 {"
3503                          "          class path {};"
3504                          "        }"
3505                          "      }"
3506                          "    }"
3507                          "  }"
3508                          "}",
3509                          cxxRecordDecl(hasName("path"), isInStdNamespace())));
3510   EXPECT_TRUE(
3511       matches("namespace std {"
3512               "  inline namespace __1 {"
3513               "    inline namespace __fs {"
3514               "      namespace filesystem {"
3515               "        inline namespace v1 {"
3516               "          class path {};"
3517               "        }"
3518               "      }"
3519               "    }"
3520               "  }"
3521               "}",
3522               cxxRecordDecl(hasName("path"),
3523                             hasAncestor(namespaceDecl(hasName("filesystem"),
3524                                                       isInStdNamespace())))));
3525 }
3526 
TEST_P(ASTMatchersTest,EqualsBoundNodeMatcher_QualType)3527 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_QualType) {
3528   EXPECT_TRUE(matches(
3529       "int i = 1;", varDecl(hasType(qualType().bind("type")),
3530                             hasInitializer(ignoringParenImpCasts(
3531                                 hasType(qualType(equalsBoundNode("type"))))))));
3532   EXPECT_TRUE(notMatches("int i = 1.f;",
3533                          varDecl(hasType(qualType().bind("type")),
3534                                  hasInitializer(ignoringParenImpCasts(hasType(
3535                                      qualType(equalsBoundNode("type"))))))));
3536 }
3537 
TEST_P(ASTMatchersTest,EqualsBoundNodeMatcher_NonMatchingTypes)3538 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_NonMatchingTypes) {
3539   EXPECT_TRUE(notMatches(
3540       "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
3541                             hasInitializer(ignoringParenImpCasts(
3542                                 hasType(qualType(equalsBoundNode("type"))))))));
3543 }
3544 
TEST_P(ASTMatchersTest,EqualsBoundNodeMatcher_Stmt)3545 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_Stmt) {
3546   EXPECT_TRUE(
3547       matches("void f() { if(1) {} }",
3548               stmt(allOf(ifStmt().bind("if"),
3549                          hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
3550 
3551   EXPECT_TRUE(notMatches(
3552       "void f() { if(1) { if (1) {} } }",
3553       stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
3554 }
3555 
TEST_P(ASTMatchersTest,EqualsBoundNodeMatcher_Decl)3556 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_Decl) {
3557   if (!GetParam().isCXX()) {
3558     // FIXME: Add a test for `equalsBoundNode()` for declarations that does not
3559     // depend on C++.
3560     return;
3561   }
3562 
3563   EXPECT_TRUE(matches(
3564       "class X { class Y {}; };",
3565       decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
3566                  hasParent(decl(has(decl(equalsBoundNode("record")))))))));
3567 
3568   EXPECT_TRUE(notMatches("class X { class Y {}; };",
3569                          decl(allOf(recordDecl(hasName("::X")).bind("record"),
3570                                     has(decl(equalsBoundNode("record")))))));
3571 }
3572 
TEST_P(ASTMatchersTest,EqualsBoundNodeMatcher_Type)3573 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_Type) {
3574   if (!GetParam().isCXX()) {
3575     // FIXME: Add a test for `equalsBoundNode()` for types that does not depend
3576     // on C++.
3577     return;
3578   }
3579   EXPECT_TRUE(matches(
3580       "class X { int a; int b; };",
3581       recordDecl(
3582           has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3583           has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
3584 
3585   EXPECT_TRUE(notMatches(
3586       "class X { int a; double b; };",
3587       recordDecl(
3588           has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3589           has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
3590 }
3591 
TEST_P(ASTMatchersTest,EqualsBoundNodeMatcher_UsingForEachDescendant)3592 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_UsingForEachDescendant) {
3593   EXPECT_TRUE(matchAndVerifyResultTrue(
3594       "int f() {"
3595       "  if (1) {"
3596       "    int i = 9;"
3597       "  }"
3598       "  int j = 10;"
3599       "  {"
3600       "    float k = 9.0;"
3601       "  }"
3602       "  return 0;"
3603       "}",
3604       // Look for variable declarations within functions whose type is the same
3605       // as the function return type.
3606       functionDecl(
3607           returns(qualType().bind("type")),
3608           forEachDescendant(varDecl(hasType(qualType(equalsBoundNode("type"))))
3609                                 .bind("decl"))),
3610       // Only i and j should match, not k.
3611       std::make_unique<VerifyIdIsBoundTo<VarDecl>>("decl", 2)));
3612 }
3613 
TEST_P(ASTMatchersTest,EqualsBoundNodeMatcher_FiltersMatchedCombinations)3614 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_FiltersMatchedCombinations) {
3615   EXPECT_TRUE(matchAndVerifyResultTrue(
3616       "void f() {"
3617       "  int x;"
3618       "  double d;"
3619       "  x = d + x - d + x;"
3620       "}",
3621       functionDecl(
3622           hasName("f"), forEachDescendant(varDecl().bind("d")),
3623           forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
3624       std::make_unique<VerifyIdIsBoundTo<VarDecl>>("d", 5)));
3625 }
3626 
TEST_P(ASTMatchersTest,EqualsBoundNodeMatcher_UnlessDescendantsOfAncestorsMatch)3627 TEST_P(ASTMatchersTest,
3628        EqualsBoundNodeMatcher_UnlessDescendantsOfAncestorsMatch) {
3629   EXPECT_TRUE(matchAndVerifyResultTrue(
3630       "struct StringRef { int size() const; const char* data() const; };"
3631       "void f(StringRef v) {"
3632       "  v.data();"
3633       "}",
3634       cxxMemberCallExpr(
3635           callee(cxxMethodDecl(hasName("data"))),
3636           on(declRefExpr(to(
3637               varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
3638           unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
3639               callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
3640               on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
3641           .bind("data"),
3642       std::make_unique<VerifyIdIsBoundTo<Expr>>("data", 1)));
3643 
3644   EXPECT_FALSE(matches(
3645       "struct StringRef { int size() const; const char* data() const; };"
3646       "void f(StringRef v) {"
3647       "  v.data();"
3648       "  v.size();"
3649       "}",
3650       cxxMemberCallExpr(
3651           callee(cxxMethodDecl(hasName("data"))),
3652           on(declRefExpr(to(
3653               varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
3654           unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
3655               callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
3656               on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
3657           .bind("data")));
3658 }
3659 
TEST_P(ASTMatchersTest,NullPointerConstant)3660 TEST_P(ASTMatchersTest, NullPointerConstant) {
3661   EXPECT_TRUE(matches("#define NULL ((void *)0)\n"
3662                       "void *v1 = NULL;",
3663                       expr(nullPointerConstant())));
3664   EXPECT_TRUE(matches("char *cp = (char *)0;", expr(nullPointerConstant())));
3665   EXPECT_TRUE(matches("int *ip = 0;", expr(nullPointerConstant())));
3666   EXPECT_FALSE(matches("int i = 0;", expr(nullPointerConstant())));
3667 }
3668 
TEST_P(ASTMatchersTest,NullPointerConstant_GNUNull)3669 TEST_P(ASTMatchersTest, NullPointerConstant_GNUNull) {
3670   if (!GetParam().isCXX()) {
3671     return;
3672   }
3673 
3674   EXPECT_TRUE(matches("void *p = __null;", expr(nullPointerConstant())));
3675 }
3676 
TEST_P(ASTMatchersTest,NullPointerConstant_GNUNullInTemplate)3677 TEST_P(ASTMatchersTest, NullPointerConstant_GNUNullInTemplate) {
3678   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3679     // FIXME: Fix this test to work with delayed template parsing.
3680     return;
3681   }
3682 
3683   const char kTest[] = R"(
3684     template <typename T>
3685     struct MyTemplate {
3686       MyTemplate() : field_(__null) {}
3687       T* field_;
3688     };
3689   )";
3690   EXPECT_TRUE(matches(kTest, expr(nullPointerConstant())));
3691 }
3692 
TEST_P(ASTMatchersTest,NullPointerConstant_CXX11Nullptr)3693 TEST_P(ASTMatchersTest, NullPointerConstant_CXX11Nullptr) {
3694   if (!GetParam().isCXX11OrLater()) {
3695     return;
3696   }
3697 
3698   EXPECT_TRUE(matches("void *p = nullptr;", expr(nullPointerConstant())));
3699 }
3700 
TEST_P(ASTMatchersTest,HasExternalFormalLinkage)3701 TEST_P(ASTMatchersTest, HasExternalFormalLinkage) {
3702   EXPECT_TRUE(matches("int a = 0;",
3703                       namedDecl(hasName("a"), hasExternalFormalLinkage())));
3704   EXPECT_TRUE(notMatches("static int a = 0;",
3705                          namedDecl(hasName("a"), hasExternalFormalLinkage())));
3706   EXPECT_TRUE(notMatches("static void f(void) { int a = 0; }",
3707                          namedDecl(hasName("a"), hasExternalFormalLinkage())));
3708   EXPECT_TRUE(notMatches("void f(void) { int a = 0; }",
3709                          namedDecl(hasName("a"), hasExternalFormalLinkage())));
3710 }
3711 
TEST_P(ASTMatchersTest,HasExternalFormalLinkage_CXX)3712 TEST_P(ASTMatchersTest, HasExternalFormalLinkage_CXX) {
3713   if (!GetParam().isCXX()) {
3714     return;
3715   }
3716 
3717   EXPECT_TRUE(notMatches("namespace { int a = 0; }",
3718                          namedDecl(hasName("a"), hasExternalFormalLinkage())));
3719 }
3720 
TEST_P(ASTMatchersTest,HasDefaultArgument)3721 TEST_P(ASTMatchersTest, HasDefaultArgument) {
3722   if (!GetParam().isCXX()) {
3723     return;
3724   }
3725 
3726   EXPECT_TRUE(
3727       matches("void x(int val = 0) {}", parmVarDecl(hasDefaultArgument())));
3728   EXPECT_TRUE(
3729       notMatches("void x(int val) {}", parmVarDecl(hasDefaultArgument())));
3730 }
3731 
TEST_P(ASTMatchersTest,IsAtPosition)3732 TEST_P(ASTMatchersTest, IsAtPosition) {
3733   EXPECT_TRUE(matches("void x(int a, int b) {}", parmVarDecl(isAtPosition(1))));
3734   EXPECT_TRUE(matches("void x(int a, int b) {}", parmVarDecl(isAtPosition(0))));
3735   EXPECT_TRUE(matches("void x(int a, int b) {}", parmVarDecl(isAtPosition(1))));
3736   EXPECT_TRUE(notMatches("void x(int val) {}", parmVarDecl(isAtPosition(1))));
3737 }
3738 
TEST_P(ASTMatchersTest,IsAtPosition_FunctionDecl)3739 TEST_P(ASTMatchersTest, IsAtPosition_FunctionDecl) {
3740   EXPECT_TRUE(matches("void x(int a);", parmVarDecl(isAtPosition(0))));
3741   EXPECT_TRUE(matches("void x(int a, int b);", parmVarDecl(isAtPosition(0))));
3742   EXPECT_TRUE(matches("void x(int a, int b);", parmVarDecl(isAtPosition(1))));
3743   EXPECT_TRUE(notMatches("void x(int val);", parmVarDecl(isAtPosition(1))));
3744 }
3745 
TEST_P(ASTMatchersTest,IsAtPosition_Lambda)3746 TEST_P(ASTMatchersTest, IsAtPosition_Lambda) {
3747   if (!GetParam().isCXX11OrLater()) {
3748     return;
3749   }
3750 
3751   EXPECT_TRUE(
3752       matches("void x() { [](int a) {};  }", parmVarDecl(isAtPosition(0))));
3753   EXPECT_TRUE(matches("void x() { [](int a, int b) {}; }",
3754                       parmVarDecl(isAtPosition(0))));
3755   EXPECT_TRUE(matches("void x() { [](int a, int b) {}; }",
3756                       parmVarDecl(isAtPosition(1))));
3757   EXPECT_TRUE(
3758       notMatches("void x() { [](int val) {}; }", parmVarDecl(isAtPosition(1))));
3759 }
3760 
TEST_P(ASTMatchersTest,IsAtPosition_BlockDecl)3761 TEST_P(ASTMatchersTest, IsAtPosition_BlockDecl) {
3762   EXPECT_TRUE(matchesObjC(
3763       "void func()  { void (^my_block)(int arg) = ^void(int arg) {}; } ",
3764       parmVarDecl(isAtPosition(0))));
3765 
3766   EXPECT_TRUE(matchesObjC("void func()  { void (^my_block)(int x, int y) = "
3767                           "^void(int x, int y) {}; } ",
3768                           parmVarDecl(isAtPosition(1))));
3769 
3770   EXPECT_TRUE(notMatchesObjC(
3771       "void func()  { void (^my_block)(int arg) = ^void(int arg) {}; } ",
3772       parmVarDecl(isAtPosition(1))));
3773 }
3774 
TEST_P(ASTMatchersTest,IsArray)3775 TEST_P(ASTMatchersTest, IsArray) {
3776   if (!GetParam().isCXX()) {
3777     return;
3778   }
3779 
3780   EXPECT_TRUE(matches("struct MyClass {}; MyClass *p1 = new MyClass[10];",
3781                       cxxNewExpr(isArray())));
3782 }
3783 
TEST_P(ASTMatchersTest,HasArraySize)3784 TEST_P(ASTMatchersTest, HasArraySize) {
3785   if (!GetParam().isCXX()) {
3786     return;
3787   }
3788 
3789   EXPECT_TRUE(matches("struct MyClass {}; MyClass *p1 = new MyClass[10];",
3790                       cxxNewExpr(hasArraySize(
3791                           ignoringParenImpCasts(integerLiteral(equals(10)))))));
3792 }
3793 
TEST_P(ASTMatchersTest,HasDefinition_MatchesStructDefinition)3794 TEST_P(ASTMatchersTest, HasDefinition_MatchesStructDefinition) {
3795   if (!GetParam().isCXX()) {
3796     return;
3797   }
3798 
3799   EXPECT_TRUE(matches("struct x {};", cxxRecordDecl(hasDefinition())));
3800   EXPECT_TRUE(notMatches("struct x;", cxxRecordDecl(hasDefinition())));
3801 }
3802 
TEST_P(ASTMatchersTest,HasDefinition_MatchesClassDefinition)3803 TEST_P(ASTMatchersTest, HasDefinition_MatchesClassDefinition) {
3804   if (!GetParam().isCXX()) {
3805     return;
3806   }
3807 
3808   EXPECT_TRUE(matches("class x {};", cxxRecordDecl(hasDefinition())));
3809   EXPECT_TRUE(notMatches("class x;", cxxRecordDecl(hasDefinition())));
3810 }
3811 
TEST_P(ASTMatchersTest,HasDefinition_MatchesUnionDefinition)3812 TEST_P(ASTMatchersTest, HasDefinition_MatchesUnionDefinition) {
3813   if (!GetParam().isCXX()) {
3814     return;
3815   }
3816 
3817   EXPECT_TRUE(matches("union x {};", cxxRecordDecl(hasDefinition())));
3818   EXPECT_TRUE(notMatches("union x;", cxxRecordDecl(hasDefinition())));
3819 }
3820 
TEST_P(ASTMatchersTest,IsScoped_MatchesScopedEnum)3821 TEST_P(ASTMatchersTest, IsScoped_MatchesScopedEnum) {
3822   if (!GetParam().isCXX11OrLater()) {
3823     return;
3824   }
3825   EXPECT_TRUE(matches("enum class X {};", enumDecl(isScoped())));
3826 }
3827 
TEST_P(ASTMatchersTest,IsScoped_NotMatchesRegularEnum)3828 TEST_P(ASTMatchersTest, IsScoped_NotMatchesRegularEnum) {
3829   EXPECT_TRUE(notMatches("enum E { E1 };", enumDecl(isScoped())));
3830 }
3831 
TEST_P(ASTMatchersTest,IsStruct)3832 TEST_P(ASTMatchersTest, IsStruct) {
3833   EXPECT_TRUE(matches("struct S {};", tagDecl(isStruct())));
3834 }
3835 
TEST_P(ASTMatchersTest,IsUnion)3836 TEST_P(ASTMatchersTest, IsUnion) {
3837   EXPECT_TRUE(matches("union U {};", tagDecl(isUnion())));
3838 }
3839 
TEST_P(ASTMatchersTest,IsEnum)3840 TEST_P(ASTMatchersTest, IsEnum) {
3841   EXPECT_TRUE(matches("enum E { E1 };", tagDecl(isEnum())));
3842 }
3843 
TEST_P(ASTMatchersTest,IsClass)3844 TEST_P(ASTMatchersTest, IsClass) {
3845   if (!GetParam().isCXX()) {
3846     return;
3847   }
3848 
3849   EXPECT_TRUE(matches("class C {};", tagDecl(isClass())));
3850 }
3851 
TEST_P(ASTMatchersTest,HasTrailingReturn_MatchesTrailingReturn)3852 TEST_P(ASTMatchersTest, HasTrailingReturn_MatchesTrailingReturn) {
3853   if (!GetParam().isCXX11OrLater()) {
3854     return;
3855   }
3856 
3857   EXPECT_TRUE(matches("auto Y() -> int { return 0; }",
3858                       functionDecl(hasTrailingReturn())));
3859   EXPECT_TRUE(matches("auto X() -> int;", functionDecl(hasTrailingReturn())));
3860   EXPECT_TRUE(
3861       notMatches("int X() { return 0; }", functionDecl(hasTrailingReturn())));
3862   EXPECT_TRUE(notMatches("int X();", functionDecl(hasTrailingReturn())));
3863   EXPECT_TRUE(notMatches("void X();", functionDecl(hasTrailingReturn())));
3864 }
3865 
TEST_P(ASTMatchersTest,HasTrailingReturn_MatchesLambdaTrailingReturn)3866 TEST_P(ASTMatchersTest, HasTrailingReturn_MatchesLambdaTrailingReturn) {
3867   if (!GetParam().isCXX11OrLater()) {
3868     return;
3869   }
3870 
3871   EXPECT_TRUE(matches(
3872       "auto lambda2 = [](double x, double y) -> double {return x + y;};",
3873       functionDecl(hasTrailingReturn())));
3874   EXPECT_TRUE(
3875       notMatches("auto lambda2 = [](double x, double y) {return x + y;};",
3876                  functionDecl(hasTrailingReturn())));
3877 }
3878 
TEST_P(ASTMatchersTest,IsAssignmentOperator)3879 TEST_P(ASTMatchersTest, IsAssignmentOperator) {
3880   if (!GetParam().isCXX()) {
3881     return;
3882   }
3883 
3884   StatementMatcher BinAsgmtOperator = binaryOperator(isAssignmentOperator());
3885   StatementMatcher CXXAsgmtOperator =
3886       cxxOperatorCallExpr(isAssignmentOperator());
3887 
3888   EXPECT_TRUE(matches("void x() { int a; a += 1; }", BinAsgmtOperator));
3889   EXPECT_TRUE(matches("void x() { int a; a = 2; }", BinAsgmtOperator));
3890   EXPECT_TRUE(matches("void x() { int a; a &= 3; }", BinAsgmtOperator));
3891   EXPECT_TRUE(matches("struct S { S& operator=(const S&); };"
3892                       "void x() { S s1, s2; s1 = s2; }",
3893                       CXXAsgmtOperator));
3894   EXPECT_TRUE(
3895       notMatches("void x() { int a; if(a == 0) return; }", BinAsgmtOperator));
3896 }
3897 
TEST_P(ASTMatchersTest,IsComparisonOperator)3898 TEST_P(ASTMatchersTest, IsComparisonOperator) {
3899   if (!GetParam().isCXX()) {
3900     return;
3901   }
3902 
3903   StatementMatcher BinCompOperator = binaryOperator(isComparisonOperator());
3904   StatementMatcher CXXCompOperator =
3905       cxxOperatorCallExpr(isComparisonOperator());
3906 
3907   EXPECT_TRUE(matches("void x() { int a; a == 1; }", BinCompOperator));
3908   EXPECT_TRUE(matches("void x() { int a; a > 2; }", BinCompOperator));
3909   EXPECT_TRUE(matches("struct S { bool operator==(const S&); };"
3910                       "void x() { S s1, s2; bool b1 = s1 == s2; }",
3911                       CXXCompOperator));
3912   EXPECT_TRUE(
3913       notMatches("void x() { int a; if(a = 0) return; }", BinCompOperator));
3914 }
3915 
TEST_P(ASTMatchersTest,HasInit)3916 TEST_P(ASTMatchersTest, HasInit) {
3917   if (!GetParam().isCXX11OrLater()) {
3918     // FIXME: Add a test for `hasInit()` that does not depend on C++.
3919     return;
3920   }
3921 
3922   EXPECT_TRUE(matches("int x{0};", initListExpr(hasInit(0, expr()))));
3923   EXPECT_FALSE(matches("int x{0};", initListExpr(hasInit(1, expr()))));
3924   EXPECT_FALSE(matches("int x;", initListExpr(hasInit(0, expr()))));
3925 }
3926 
TEST_P(ASTMatchersTest,IsMain)3927 TEST_P(ASTMatchersTest, IsMain) {
3928   EXPECT_TRUE(matches("int main() {}", functionDecl(isMain())));
3929 
3930   EXPECT_TRUE(notMatches("int main2() {}", functionDecl(isMain())));
3931 }
3932 
TEST_P(ASTMatchersTest,OMPExecutableDirective_IsStandaloneDirective)3933 TEST_P(ASTMatchersTest, OMPExecutableDirective_IsStandaloneDirective) {
3934   auto Matcher = ompExecutableDirective(isStandaloneDirective());
3935 
3936   StringRef Source0 = R"(
3937 void x() {
3938 #pragma omp parallel
3939 ;
3940 })";
3941   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
3942 
3943   StringRef Source1 = R"(
3944 void x() {
3945 #pragma omp taskyield
3946 })";
3947   EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
3948 }
3949 
TEST_P(ASTMatchersTest,OMPExecutableDirective_HasStructuredBlock)3950 TEST_P(ASTMatchersTest, OMPExecutableDirective_HasStructuredBlock) {
3951   StringRef Source0 = R"(
3952 void x() {
3953 #pragma omp parallel
3954 ;
3955 })";
3956   EXPECT_TRUE(matchesWithOpenMP(
3957       Source0, ompExecutableDirective(hasStructuredBlock(nullStmt()))));
3958 
3959   StringRef Source1 = R"(
3960 void x() {
3961 #pragma omp parallel
3962 {;}
3963 })";
3964   EXPECT_TRUE(notMatchesWithOpenMP(
3965       Source1, ompExecutableDirective(hasStructuredBlock(nullStmt()))));
3966   EXPECT_TRUE(matchesWithOpenMP(
3967       Source1, ompExecutableDirective(hasStructuredBlock(compoundStmt()))));
3968 
3969   StringRef Source2 = R"(
3970 void x() {
3971 #pragma omp taskyield
3972 {;}
3973 })";
3974   EXPECT_TRUE(notMatchesWithOpenMP(
3975       Source2, ompExecutableDirective(hasStructuredBlock(anything()))));
3976 }
3977 
TEST_P(ASTMatchersTest,OMPExecutableDirective_HasClause)3978 TEST_P(ASTMatchersTest, OMPExecutableDirective_HasClause) {
3979   auto Matcher = ompExecutableDirective(hasAnyClause(anything()));
3980 
3981   StringRef Source0 = R"(
3982 void x() {
3983 ;
3984 })";
3985   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
3986 
3987   StringRef Source1 = R"(
3988 void x() {
3989 #pragma omp parallel
3990 ;
3991 })";
3992   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
3993 
3994   StringRef Source2 = R"(
3995 void x() {
3996 #pragma omp parallel default(none)
3997 ;
3998 })";
3999   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
4000 
4001   StringRef Source3 = R"(
4002 void x() {
4003 #pragma omp parallel default(shared)
4004 ;
4005 })";
4006   EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
4007 
4008   StringRef Source4 = R"(
4009 void x() {
4010 #pragma omp parallel default(firstprivate)
4011 ;
4012 })";
4013   EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
4014 
4015   StringRef Source5 = R"(
4016 void x(int x) {
4017 #pragma omp parallel num_threads(x)
4018 ;
4019 })";
4020   EXPECT_TRUE(matchesWithOpenMP(Source5, Matcher));
4021 }
4022 
TEST_P(ASTMatchersTest,OMPDefaultClause_IsNoneKind)4023 TEST_P(ASTMatchersTest, OMPDefaultClause_IsNoneKind) {
4024   auto Matcher =
4025       ompExecutableDirective(hasAnyClause(ompDefaultClause(isNoneKind())));
4026 
4027   StringRef Source0 = R"(
4028 void x() {
4029 ;
4030 })";
4031   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4032 
4033   StringRef Source1 = R"(
4034 void x() {
4035 #pragma omp parallel
4036 ;
4037 })";
4038   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
4039 
4040   StringRef Source2 = R"(
4041 void x() {
4042 #pragma omp parallel default(none)
4043 ;
4044 })";
4045   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
4046 
4047   StringRef Source3 = R"(
4048 void x() {
4049 #pragma omp parallel default(shared)
4050 ;
4051 })";
4052   EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
4053 
4054   StringRef Source4 = R"(
4055 void x(int x) {
4056 #pragma omp parallel default(firstprivate)
4057 ;
4058 })";
4059   EXPECT_TRUE(notMatchesWithOpenMP51(Source4, Matcher));
4060 
4061   const std::string Source5 = R"(
4062 void x(int x) {
4063 #pragma omp parallel num_threads(x)
4064 ;
4065 })";
4066   EXPECT_TRUE(notMatchesWithOpenMP(Source5, Matcher));
4067 }
4068 
TEST_P(ASTMatchersTest,OMPDefaultClause_IsSharedKind)4069 TEST_P(ASTMatchersTest, OMPDefaultClause_IsSharedKind) {
4070   auto Matcher =
4071       ompExecutableDirective(hasAnyClause(ompDefaultClause(isSharedKind())));
4072 
4073   StringRef Source0 = R"(
4074 void x() {
4075 ;
4076 })";
4077   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4078 
4079   StringRef Source1 = R"(
4080 void x() {
4081 #pragma omp parallel
4082 ;
4083 })";
4084   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
4085 
4086   StringRef Source2 = R"(
4087 void x() {
4088 #pragma omp parallel default(shared)
4089 ;
4090 })";
4091   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
4092 
4093   StringRef Source3 = R"(
4094 void x() {
4095 #pragma omp parallel default(none)
4096 ;
4097 })";
4098   EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
4099 
4100   StringRef Source4 = R"(
4101 void x(int x) {
4102 #pragma omp parallel default(firstprivate)
4103 ;
4104 })";
4105   EXPECT_TRUE(notMatchesWithOpenMP51(Source4, Matcher));
4106 
4107   const std::string Source5 = R"(
4108 void x(int x) {
4109 #pragma omp parallel num_threads(x)
4110 ;
4111 })";
4112   EXPECT_TRUE(notMatchesWithOpenMP(Source5, Matcher));
4113 }
4114 
TEST(OMPDefaultClause,isFirstPrivateKind)4115 TEST(OMPDefaultClause, isFirstPrivateKind) {
4116   auto Matcher = ompExecutableDirective(
4117       hasAnyClause(ompDefaultClause(isFirstPrivateKind())));
4118 
4119   const std::string Source0 = R"(
4120 void x() {
4121 ;
4122 })";
4123   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4124 
4125   const std::string Source1 = R"(
4126 void x() {
4127 #pragma omp parallel
4128 ;
4129 })";
4130   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
4131 
4132   const std::string Source2 = R"(
4133 void x() {
4134 #pragma omp parallel default(shared)
4135 ;
4136 })";
4137   EXPECT_TRUE(notMatchesWithOpenMP(Source2, Matcher));
4138 
4139   const std::string Source3 = R"(
4140 void x() {
4141 #pragma omp parallel default(none)
4142 ;
4143 })";
4144   EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
4145 
4146   const std::string Source4 = R"(
4147 void x(int x) {
4148 #pragma omp parallel default(firstprivate)
4149 ;
4150 })";
4151   EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
4152 
4153   const std::string Source5 = R"(
4154 void x(int x) {
4155 #pragma omp parallel num_threads(x)
4156 ;
4157 })";
4158   EXPECT_TRUE(notMatchesWithOpenMP(Source5, Matcher));
4159 }
4160 
TEST_P(ASTMatchersTest,OMPExecutableDirective_IsAllowedToContainClauseKind)4161 TEST_P(ASTMatchersTest, OMPExecutableDirective_IsAllowedToContainClauseKind) {
4162   auto Matcher = ompExecutableDirective(
4163       isAllowedToContainClauseKind(llvm::omp::OMPC_default));
4164 
4165   StringRef Source0 = R"(
4166 void x() {
4167 ;
4168 })";
4169   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4170 
4171   StringRef Source1 = R"(
4172 void x() {
4173 #pragma omp parallel
4174 ;
4175 })";
4176   EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
4177 
4178   StringRef Source2 = R"(
4179 void x() {
4180 #pragma omp parallel default(none)
4181 ;
4182 })";
4183   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
4184 
4185   StringRef Source3 = R"(
4186 void x() {
4187 #pragma omp parallel default(shared)
4188 ;
4189 })";
4190   EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
4191 
4192   StringRef Source4 = R"(
4193 void x() {
4194 #pragma omp parallel default(firstprivate)
4195 ;
4196 })";
4197   EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
4198 
4199   StringRef Source5 = R"(
4200 void x(int x) {
4201 #pragma omp parallel num_threads(x)
4202 ;
4203 })";
4204   EXPECT_TRUE(matchesWithOpenMP(Source5, Matcher));
4205 
4206   StringRef Source6 = R"(
4207 void x() {
4208 #pragma omp taskyield
4209 })";
4210   EXPECT_TRUE(notMatchesWithOpenMP(Source6, Matcher));
4211 
4212   StringRef Source7 = R"(
4213 void x() {
4214 #pragma omp task
4215 ;
4216 })";
4217   EXPECT_TRUE(matchesWithOpenMP(Source7, Matcher));
4218 }
4219 
TEST_P(ASTMatchersTest,HasAnyBase_DirectBase)4220 TEST_P(ASTMatchersTest, HasAnyBase_DirectBase) {
4221   if (!GetParam().isCXX()) {
4222     return;
4223   }
4224   EXPECT_TRUE(matches(
4225       "struct Base {};"
4226       "struct ExpectedMatch : Base {};",
4227       cxxRecordDecl(hasName("ExpectedMatch"),
4228                     hasAnyBase(hasType(cxxRecordDecl(hasName("Base")))))));
4229 }
4230 
TEST_P(ASTMatchersTest,HasAnyBase_IndirectBase)4231 TEST_P(ASTMatchersTest, HasAnyBase_IndirectBase) {
4232   if (!GetParam().isCXX()) {
4233     return;
4234   }
4235   EXPECT_TRUE(matches(
4236       "struct Base {};"
4237       "struct Intermediate : Base {};"
4238       "struct ExpectedMatch : Intermediate {};",
4239       cxxRecordDecl(hasName("ExpectedMatch"),
4240                     hasAnyBase(hasType(cxxRecordDecl(hasName("Base")))))));
4241 }
4242 
TEST_P(ASTMatchersTest,HasAnyBase_NoBase)4243 TEST_P(ASTMatchersTest, HasAnyBase_NoBase) {
4244   if (!GetParam().isCXX()) {
4245     return;
4246   }
4247   EXPECT_TRUE(notMatches("struct Foo {};"
4248                          "struct Bar {};",
4249                          cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl())))));
4250 }
4251 
TEST_P(ASTMatchersTest,HasAnyBase_IsPublic_Public)4252 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_Public) {
4253   if (!GetParam().isCXX()) {
4254     return;
4255   }
4256   EXPECT_TRUE(matches("class Base {};"
4257                       "class Derived : public Base {};",
4258                       cxxRecordDecl(hasAnyBase(isPublic()))));
4259 }
4260 
TEST_P(ASTMatchersTest,HasAnyBase_IsPublic_DefaultAccessSpecifierPublic)4261 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_DefaultAccessSpecifierPublic) {
4262   if (!GetParam().isCXX()) {
4263     return;
4264   }
4265   EXPECT_TRUE(matches("class Base {};"
4266                       "struct Derived : Base {};",
4267                       cxxRecordDecl(hasAnyBase(isPublic()))));
4268 }
4269 
TEST_P(ASTMatchersTest,HasAnyBase_IsPublic_Private)4270 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_Private) {
4271   if (!GetParam().isCXX()) {
4272     return;
4273   }
4274   EXPECT_TRUE(notMatches("class Base {};"
4275                          "class Derived : private Base {};",
4276                          cxxRecordDecl(hasAnyBase(isPublic()))));
4277 }
4278 
TEST_P(ASTMatchersTest,HasAnyBase_IsPublic_DefaultAccessSpecifierPrivate)4279 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_DefaultAccessSpecifierPrivate) {
4280   if (!GetParam().isCXX()) {
4281     return;
4282   }
4283   EXPECT_TRUE(notMatches("class Base {};"
4284                          "class Derived : Base {};",
4285                          cxxRecordDecl(hasAnyBase(isPublic()))));
4286 }
4287 
TEST_P(ASTMatchersTest,HasAnyBase_IsPublic_Protected)4288 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_Protected) {
4289   if (!GetParam().isCXX()) {
4290     return;
4291   }
4292   EXPECT_TRUE(notMatches("class Base {};"
4293                          "class Derived : protected Base {};",
4294                          cxxRecordDecl(hasAnyBase(isPublic()))));
4295 }
4296 
TEST_P(ASTMatchersTest,HasAnyBase_IsPrivate_Private)4297 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_Private) {
4298   if (!GetParam().isCXX()) {
4299     return;
4300   }
4301   EXPECT_TRUE(matches("class Base {};"
4302                       "class Derived : private Base {};",
4303                       cxxRecordDecl(hasAnyBase(isPrivate()))));
4304 }
4305 
TEST_P(ASTMatchersTest,HasAnyBase_IsPrivate_DefaultAccessSpecifierPrivate)4306 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_DefaultAccessSpecifierPrivate) {
4307   if (!GetParam().isCXX()) {
4308     return;
4309   }
4310   EXPECT_TRUE(matches("struct Base {};"
4311                       "class Derived : Base {};",
4312                       cxxRecordDecl(hasAnyBase(isPrivate()))));
4313 }
4314 
TEST_P(ASTMatchersTest,HasAnyBase_IsPrivate_Public)4315 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_Public) {
4316   if (!GetParam().isCXX()) {
4317     return;
4318   }
4319   EXPECT_TRUE(notMatches("class Base {};"
4320                          "class Derived : public Base {};",
4321                          cxxRecordDecl(hasAnyBase(isPrivate()))));
4322 }
4323 
TEST_P(ASTMatchersTest,HasAnyBase_IsPrivate_DefaultAccessSpecifierPublic)4324 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_DefaultAccessSpecifierPublic) {
4325   if (!GetParam().isCXX()) {
4326     return;
4327   }
4328   EXPECT_TRUE(notMatches("class Base {};"
4329                          "struct Derived : Base {};",
4330                          cxxRecordDecl(hasAnyBase(isPrivate()))));
4331 }
4332 
TEST_P(ASTMatchersTest,HasAnyBase_IsPrivate_Protected)4333 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_Protected) {
4334   if (!GetParam().isCXX()) {
4335     return;
4336   }
4337   EXPECT_TRUE(notMatches("class Base {};"
4338                          "class Derived : protected Base {};",
4339                          cxxRecordDecl(hasAnyBase(isPrivate()))));
4340 }
4341 
TEST_P(ASTMatchersTest,HasAnyBase_IsProtected_Protected)4342 TEST_P(ASTMatchersTest, HasAnyBase_IsProtected_Protected) {
4343   if (!GetParam().isCXX()) {
4344     return;
4345   }
4346   EXPECT_TRUE(matches("class Base {};"
4347                       "class Derived : protected Base {};",
4348                       cxxRecordDecl(hasAnyBase(isProtected()))));
4349 }
4350 
TEST_P(ASTMatchersTest,HasAnyBase_IsProtected_Public)4351 TEST_P(ASTMatchersTest, HasAnyBase_IsProtected_Public) {
4352   if (!GetParam().isCXX()) {
4353     return;
4354   }
4355   EXPECT_TRUE(notMatches("class Base {};"
4356                          "class Derived : public Base {};",
4357                          cxxRecordDecl(hasAnyBase(isProtected()))));
4358 }
4359 
TEST_P(ASTMatchersTest,HasAnyBase_IsProtected_Private)4360 TEST_P(ASTMatchersTest, HasAnyBase_IsProtected_Private) {
4361   if (!GetParam().isCXX()) {
4362     return;
4363   }
4364   EXPECT_TRUE(notMatches("class Base {};"
4365                          "class Derived : private Base {};",
4366                          cxxRecordDecl(hasAnyBase(isProtected()))));
4367 }
4368 
TEST_P(ASTMatchersTest,HasAnyBase_IsVirtual_Directly)4369 TEST_P(ASTMatchersTest, HasAnyBase_IsVirtual_Directly) {
4370   if (!GetParam().isCXX()) {
4371     return;
4372   }
4373   EXPECT_TRUE(matches("class Base {};"
4374                       "class Derived : virtual Base {};",
4375                       cxxRecordDecl(hasAnyBase(isVirtual()))));
4376 }
4377 
TEST_P(ASTMatchersTest,HasAnyBase_IsVirtual_Indirectly)4378 TEST_P(ASTMatchersTest, HasAnyBase_IsVirtual_Indirectly) {
4379   if (!GetParam().isCXX()) {
4380     return;
4381   }
4382   EXPECT_TRUE(
4383       matches("class Base {};"
4384               "class Intermediate : virtual Base {};"
4385               "class Derived : Intermediate {};",
4386               cxxRecordDecl(hasName("Derived"), hasAnyBase(isVirtual()))));
4387 }
4388 
TEST_P(ASTMatchersTest,HasAnyBase_IsVirtual_NoVirtualBase)4389 TEST_P(ASTMatchersTest, HasAnyBase_IsVirtual_NoVirtualBase) {
4390   if (!GetParam().isCXX()) {
4391     return;
4392   }
4393   EXPECT_TRUE(notMatches("class Base {};"
4394                          "class Derived : Base {};",
4395                          cxxRecordDecl(hasAnyBase(isVirtual()))));
4396 }
4397 
TEST_P(ASTMatchersTest,HasDirectBase)4398 TEST_P(ASTMatchersTest, HasDirectBase) {
4399   if (!GetParam().isCXX()) {
4400     return;
4401   }
4402 
4403   DeclarationMatcher ClassHasAnyDirectBase =
4404       cxxRecordDecl(hasDirectBase(cxxBaseSpecifier()));
4405   EXPECT_TRUE(notMatches("class X {};", ClassHasAnyDirectBase));
4406   EXPECT_TRUE(matches("class X {}; class Y : X {};", ClassHasAnyDirectBase));
4407   EXPECT_TRUE(matches("class X {}; class Y : public virtual X {};",
4408                       ClassHasAnyDirectBase));
4409 
4410   EXPECT_TRUE(matches(
4411       R"cc(
4412     class Base {};
4413     class Derived : Base{};
4414     )cc",
4415       cxxRecordDecl(hasName("Derived"),
4416                     hasDirectBase(hasType(cxxRecordDecl(hasName("Base")))))));
4417 
4418   StringRef MultiDerived = R"cc(
4419     class Base {};
4420     class Base2 {};
4421     class Derived : Base, Base2{};
4422     )cc";
4423 
4424   EXPECT_TRUE(matches(
4425       MultiDerived,
4426       cxxRecordDecl(hasName("Derived"),
4427                     hasDirectBase(hasType(cxxRecordDecl(hasName("Base")))))));
4428   EXPECT_TRUE(matches(
4429       MultiDerived,
4430       cxxRecordDecl(hasName("Derived"),
4431                     hasDirectBase(hasType(cxxRecordDecl(hasName("Base2")))))));
4432 
4433   StringRef Indirect = R"cc(
4434     class Base {};
4435     class Intermediate : Base {};
4436     class Derived : Intermediate{};
4437     )cc";
4438 
4439   EXPECT_TRUE(
4440       matches(Indirect, cxxRecordDecl(hasName("Derived"),
4441                                       hasDirectBase(hasType(cxxRecordDecl(
4442                                           hasName("Intermediate")))))));
4443   EXPECT_TRUE(notMatches(
4444       Indirect,
4445       cxxRecordDecl(hasName("Derived"),
4446                     hasDirectBase(hasType(cxxRecordDecl(hasName("Base")))))));
4447 }
4448 } // namespace ast_matchers
4449 } // namespace clang
4450