]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - unittests/ASTMatchers/ASTMatchersNodeTest.cpp
Vendor import of clang trunk r338150:
[FreeBSD/FreeBSD.git] / unittests / ASTMatchers / ASTMatchersNodeTest.cpp
1 //== unittests/ASTMatchers/ASTMatchersNodeTest.cpp - AST matcher unit tests ==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "ASTMatchersTest.h"
11 #include "clang/AST/PrettyPrinter.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/ASTMatchers/ASTMatchers.h"
14 #include "clang/Tooling/Tooling.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/Support/Host.h"
17 #include "gtest/gtest.h"
18
19 namespace clang {
20 namespace ast_matchers {
21
22 TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
23   MatchFinder Finder;
24   EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
25   EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
26   EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
27                                        nullptr));
28
29   // Do not accept non-toplevel matchers.
30   EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
31   EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
32 }
33
34 TEST(Decl, MatchesDeclarations) {
35   EXPECT_TRUE(notMatches("", decl(usingDecl())));
36   EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
37                       decl(usingDecl())));
38 }
39
40 TEST(NameableDeclaration, MatchesVariousDecls) {
41   DeclarationMatcher NamedX = namedDecl(hasName("X"));
42   EXPECT_TRUE(matches("typedef int X;", NamedX));
43   EXPECT_TRUE(matches("int X;", NamedX));
44   EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
45   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
46   EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
47   EXPECT_TRUE(matches("namespace X { }", NamedX));
48   EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
49
50   EXPECT_TRUE(notMatches("#define X 1", NamedX));
51 }
52
53 TEST(NameableDeclaration, REMatchesVariousDecls) {
54   DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
55   EXPECT_TRUE(matches("typedef int Xa;", NamedX));
56   EXPECT_TRUE(matches("int Xb;", NamedX));
57   EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
58   EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
59   EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
60   EXPECT_TRUE(matches("namespace Xij { }", NamedX));
61   EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
62
63   EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
64
65   DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
66   EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
67   EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
68
69   DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
70   EXPECT_TRUE(matches("int abc;", Abc));
71   EXPECT_TRUE(matches("int aFOObBARc;", Abc));
72   EXPECT_TRUE(notMatches("int cab;", Abc));
73   EXPECT_TRUE(matches("int cabc;", Abc));
74
75   DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
76   EXPECT_TRUE(matches("int k;", StartsWithK));
77   EXPECT_TRUE(matches("int kAbc;", StartsWithK));
78   EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
79   EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
80   EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
81 }
82
83 TEST(DeclarationMatcher, MatchClass) {
84   DeclarationMatcher ClassMatcher(recordDecl());
85
86   // This passes on Windows only because we explicitly pass -target
87   // i386-unknown-unknown.  If we were to compile with the default target
88   // triple, we'd want to EXPECT_TRUE if it's Win32 or MSVC.
89   EXPECT_FALSE(matches("", ClassMatcher));
90
91   DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
92   EXPECT_TRUE(matches("class X;", ClassX));
93   EXPECT_TRUE(matches("class X {};", ClassX));
94   EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
95   EXPECT_TRUE(notMatches("", ClassX));
96 }
97
98 TEST(DeclarationMatcher, translationUnitDecl) {
99   const std::string Code = "int MyVar1;\n"
100     "namespace NameSpace {\n"
101     "int MyVar2;\n"
102     "}  // namespace NameSpace\n";
103   EXPECT_TRUE(matches(
104     Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
105   EXPECT_FALSE(matches(
106     Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
107   EXPECT_TRUE(matches(
108     Code,
109     varDecl(hasName("MyVar2"),
110             hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
111 }
112
113 TEST(DeclarationMatcher, LinkageSpecification) {
114   EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
115   EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
116 }
117
118 TEST(ClassTemplate, DoesNotMatchClass) {
119   DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
120   EXPECT_TRUE(notMatches("class X;", ClassX));
121   EXPECT_TRUE(notMatches("class X {};", ClassX));
122 }
123
124 TEST(ClassTemplate, MatchesClassTemplate) {
125   DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
126   EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
127   EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
128 }
129
130 TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
131   EXPECT_TRUE(notMatches("template<typename T> class X { };"
132                            "template<> class X<int> { int a; };",
133                          classTemplateDecl(hasName("X"),
134                                            hasDescendant(fieldDecl(hasName("a"))))));
135 }
136
137 TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
138   EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
139                            "template<typename T> class X<T, int> { int a; };",
140                          classTemplateDecl(hasName("X"),
141                                            hasDescendant(fieldDecl(hasName("a"))))));
142 }
143
144 TEST(DeclarationMatcher, MatchCudaDecl) {
145   EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
146                                 "void g() { f<<<1, 2>>>(); }",
147                               cudaKernelCallExpr()));
148   EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
149                               hasAttr(clang::attr::CUDADevice)));
150   EXPECT_TRUE(notMatchesWithCuda("void f() {}",
151                                  cudaKernelCallExpr()));
152   EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
153                                   hasAttr(clang::attr::CUDAGlobal)));
154 }
155
156 TEST(ValueDecl, Matches) {
157   EXPECT_TRUE(matches("enum EnumType { EnumValue };",
158                       valueDecl(hasType(asString("enum EnumType")))));
159   EXPECT_TRUE(matches("void FunctionDecl();",
160                       valueDecl(hasType(asString("void (void)")))));
161 }
162
163 TEST(FriendDecl, Matches) {
164   EXPECT_TRUE(matches("class Y { friend class X; };",
165                       friendDecl(hasType(asString("class X")))));
166   EXPECT_TRUE(matches("class Y { friend class X; };",
167                       friendDecl(hasType(recordDecl(hasName("X"))))));
168
169   EXPECT_TRUE(matches("class Y { friend void f(); };",
170                       functionDecl(hasName("f"), hasParent(friendDecl()))));
171 }
172
173 TEST(Enum, DoesNotMatchClasses) {
174   EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
175 }
176
177 TEST(Enum, MatchesEnums) {
178   EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
179 }
180
181 TEST(EnumConstant, Matches) {
182   DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
183   EXPECT_TRUE(matches("enum X{ A };", Matcher));
184   EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
185   EXPECT_TRUE(notMatches("enum X {};", Matcher));
186 }
187
188 TEST(Matcher, UnresolvedLookupExpr) {
189   // FIXME: The test is known to be broken on Windows with delayed template
190   // parsing.
191   EXPECT_TRUE(matchesConditionally("template<typename T>"
192                                    "T foo() { T a; return a; }"
193                                    "template<typename T>"
194                                    "void bar() {"
195                                    "  foo<T>();"
196                                    "}",
197                                    unresolvedLookupExpr(),
198                                    /*ExpectMatch=*/true,
199                                    "-fno-delayed-template-parsing"));
200 }
201
202 TEST(Matcher, Call) {
203   // FIXME: Do we want to overload Call() to directly take
204   // Matcher<Decl>, too?
205   StatementMatcher MethodX =
206     callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
207
208   EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
209   EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
210
211   StatementMatcher MethodOnY =
212     cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
213
214   EXPECT_TRUE(
215     matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
216             MethodOnY));
217   EXPECT_TRUE(
218     matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
219             MethodOnY));
220   EXPECT_TRUE(
221     notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
222                MethodOnY));
223   EXPECT_TRUE(
224     notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
225                MethodOnY));
226   EXPECT_TRUE(
227     notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
228                MethodOnY));
229
230   StatementMatcher MethodOnYPointer =
231     cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
232
233   EXPECT_TRUE(
234     matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
235             MethodOnYPointer));
236   EXPECT_TRUE(
237     matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
238             MethodOnYPointer));
239   EXPECT_TRUE(
240     matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
241             MethodOnYPointer));
242   EXPECT_TRUE(
243     notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
244                MethodOnYPointer));
245   EXPECT_TRUE(
246     notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
247                MethodOnYPointer));
248 }
249 TEST(Matcher, Lambda) {
250   EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
251                       lambdaExpr()));
252 }
253
254 TEST(Matcher, ForRange) {
255   EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
256                         "void f() { for (auto &a : as); }",
257                       cxxForRangeStmt()));
258   EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
259                          cxxForRangeStmt()));
260 }
261
262 TEST(Matcher, SubstNonTypeTemplateParm) {
263   EXPECT_FALSE(matches("template<int N>\n"
264                          "struct A {  static const int n = 0; };\n"
265                          "struct B : public A<42> {};",
266                        substNonTypeTemplateParmExpr()));
267   EXPECT_TRUE(matches("template<int N>\n"
268                         "struct A {  static const int n = N; };\n"
269                         "struct B : public A<42> {};",
270                       substNonTypeTemplateParmExpr()));
271 }
272
273 TEST(Matcher, NonTypeTemplateParmDecl) {
274   EXPECT_TRUE(matches("template <int N> void f();",
275                       nonTypeTemplateParmDecl(hasName("N"))));
276   EXPECT_TRUE(
277     notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
278 }
279
280 TEST(Matcher, templateTypeParmDecl) {
281   EXPECT_TRUE(matches("template <typename T> void f();",
282                       templateTypeParmDecl(hasName("T"))));
283   EXPECT_TRUE(
284     notMatches("template <int N> void f();", templateTypeParmDecl()));
285 }
286
287 TEST(Matcher, UserDefinedLiteral) {
288   EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
289                         "  return i + 1;"
290                         "}"
291                         "char c = 'a'_inc;",
292                       userDefinedLiteral()));
293 }
294
295 TEST(Matcher, FlowControl) {
296   EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
297   EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
298                       continueStmt()));
299   EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
300   EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}",
301                       labelStmt(
302                         hasDeclaration(
303                           labelDecl(hasName("FOO"))))));
304   EXPECT_TRUE(matches("void f() { FOO: ; void *ptr = &&FOO; goto *ptr; }",
305                       addrLabelExpr()));
306   EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
307 }
308
309 TEST(Matcher, OverloadedOperatorCall) {
310   StatementMatcher OpCall = cxxOperatorCallExpr();
311   // Unary operator
312   EXPECT_TRUE(matches("class Y { }; "
313                         "bool operator!(Y x) { return false; }; "
314                         "Y y; bool c = !y;", OpCall));
315   // No match -- special operators like "new", "delete"
316   // FIXME: operator new takes size_t, for which we need stddef.h, for which
317   // we need to figure out include paths in the test.
318   // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
319   //             "class Y { }; "
320   //             "void *operator new(size_t size) { return 0; } "
321   //             "Y *y = new Y;", OpCall));
322   EXPECT_TRUE(notMatches("class Y { }; "
323                            "void operator delete(void *p) { } "
324                            "void a() {Y *y = new Y; delete y;}", OpCall));
325   // Binary operator
326   EXPECT_TRUE(matches("class Y { }; "
327                         "bool operator&&(Y x, Y y) { return true; }; "
328                         "Y a; Y b; bool c = a && b;",
329                       OpCall));
330   // No match -- normal operator, not an overloaded one.
331   EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
332   EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
333 }
334
335 TEST(Matcher, ThisPointerType) {
336   StatementMatcher MethodOnY =
337     cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
338
339   EXPECT_TRUE(
340     matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
341             MethodOnY));
342   EXPECT_TRUE(
343     matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
344             MethodOnY));
345   EXPECT_TRUE(
346     matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
347             MethodOnY));
348   EXPECT_TRUE(
349     matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
350             MethodOnY));
351   EXPECT_TRUE(
352     matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
353             MethodOnY));
354
355   EXPECT_TRUE(matches(
356     "class Y {"
357       "  public: virtual void x();"
358       "};"
359       "class X : public Y {"
360       "  public: virtual void x();"
361       "};"
362       "void z() { X *x; x->Y::x(); }", MethodOnY));
363 }
364
365 TEST(Matcher, VariableUsage) {
366   StatementMatcher Reference =
367     declRefExpr(to(
368       varDecl(hasInitializer(
369         cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
370
371   EXPECT_TRUE(matches(
372     "class Y {"
373       " public:"
374       "  bool x() const;"
375       "};"
376       "void z(const Y &y) {"
377       "  bool b = y.x();"
378       "  if (b) {}"
379       "}", Reference));
380
381   EXPECT_TRUE(notMatches(
382     "class Y {"
383       " public:"
384       "  bool x() const;"
385       "};"
386       "void z(const Y &y) {"
387       "  bool b = y.x();"
388       "}", Reference));
389 }
390
391 TEST(Matcher, CalledVariable) {
392   StatementMatcher CallOnVariableY =
393     cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
394
395   EXPECT_TRUE(matches(
396     "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
397   EXPECT_TRUE(matches(
398     "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
399   EXPECT_TRUE(matches(
400     "class Y { public: void x(); };"
401       "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
402   EXPECT_TRUE(matches(
403     "class Y { public: void x(); };"
404       "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
405   EXPECT_TRUE(notMatches(
406     "class Y { public: void x(); };"
407       "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
408     CallOnVariableY));
409 }
410
411 TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
412   EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
413                       unaryExprOrTypeTraitExpr()));
414   EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
415                          alignOfExpr(anything())));
416   // FIXME: Uncomment once alignof is enabled.
417   // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
418   //                     unaryExprOrTypeTraitExpr()));
419   // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
420   //                        sizeOfExpr()));
421 }
422
423 TEST(MemberExpression, DoesNotMatchClasses) {
424   EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
425 }
426
427 TEST(MemberExpression, MatchesMemberFunctionCall) {
428   EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
429 }
430
431 TEST(MemberExpression, MatchesVariable) {
432   EXPECT_TRUE(
433     matches("class Y { void x() { this->y; } int y; };", memberExpr()));
434   EXPECT_TRUE(
435     matches("class Y { void x() { y; } int y; };", memberExpr()));
436   EXPECT_TRUE(
437     matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
438 }
439
440 TEST(MemberExpression, MatchesStaticVariable) {
441   EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
442                       memberExpr()));
443   EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
444                          memberExpr()));
445   EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
446                          memberExpr()));
447 }
448
449 TEST(Function, MatchesFunctionDeclarations) {
450   StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
451
452   EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
453   EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
454
455   if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
456     llvm::Triple::Win32) {
457     // FIXME: Make this work for MSVC.
458     // Dependent contexts, but a non-dependent call.
459     EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
460                         CallFunctionF));
461     EXPECT_TRUE(
462       matches("void f(); template <int N> struct S { void g() { f(); } };",
463               CallFunctionF));
464   }
465
466   // Depedent calls don't match.
467   EXPECT_TRUE(
468     notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
469                CallFunctionF));
470   EXPECT_TRUE(
471     notMatches("void f(int);"
472                  "template <typename T> struct S { void g(T t) { f(t); } };",
473                CallFunctionF));
474
475   EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
476   EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
477   EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
478                          functionDecl(isVariadic())));
479   EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
480   EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
481   EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
482   EXPECT_TRUE(matchesC("void f();", functionDecl(parameterCountIs(0))));
483   EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
484 }
485
486 TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
487   EXPECT_TRUE(
488     matches("template <typename T> void f(T t) {}",
489             functionTemplateDecl(hasName("f"))));
490 }
491
492 TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
493   EXPECT_TRUE(
494     notMatches("void f(double d); void f(int t) {}",
495                functionTemplateDecl(hasName("f"))));
496 }
497
498 TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
499   EXPECT_TRUE(
500     notMatches("void g(); template <typename T> void f(T t) {}"
501                  "template <> void f(int t) { g(); }",
502                functionTemplateDecl(hasName("f"),
503                                     hasDescendant(declRefExpr(to(
504                                       functionDecl(hasName("g"))))))));
505 }
506
507 TEST(Matcher, MatchesClassTemplateSpecialization) {
508   EXPECT_TRUE(matches("template<typename T> struct A {};"
509                         "template<> struct A<int> {};",
510                       classTemplateSpecializationDecl()));
511   EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
512                       classTemplateSpecializationDecl()));
513   EXPECT_TRUE(notMatches("template<typename T> struct A {};",
514                          classTemplateSpecializationDecl()));
515 }
516
517 TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
518   EXPECT_TRUE(matches("int x;", declaratorDecl()));
519   EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
520 }
521
522 TEST(ParmVarDecl, MatchesParmVars) {
523   EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
524   EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
525 }
526
527 TEST(Matcher, ConstructorCall) {
528   StatementMatcher Constructor = cxxConstructExpr();
529
530   EXPECT_TRUE(
531     matches("class X { public: X(); }; void x() { X x; }", Constructor));
532   EXPECT_TRUE(
533     matches("class X { public: X(); }; void x() { X x = X(); }",
534             Constructor));
535   EXPECT_TRUE(
536     matches("class X { public: X(int); }; void x() { X x = 0; }",
537             Constructor));
538   EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
539 }
540
541 TEST(Match, ConstructorInitializers) {
542   EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };",
543                       cxxCtorInitializer(forField(hasName("i")))));
544 }
545
546 TEST(Matcher, ThisExpr) {
547   EXPECT_TRUE(
548     matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
549   EXPECT_TRUE(
550     notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
551 }
552
553 TEST(Matcher, BindTemporaryExpression) {
554   StatementMatcher TempExpression = cxxBindTemporaryExpr();
555
556   std::string ClassString = "class string { public: string(); ~string(); }; ";
557
558   EXPECT_TRUE(
559     matches(ClassString +
560               "string GetStringByValue();"
561                 "void FunctionTakesString(string s);"
562                 "void run() { FunctionTakesString(GetStringByValue()); }",
563             TempExpression));
564
565   EXPECT_TRUE(
566     notMatches(ClassString +
567                  "string* GetStringPointer(); "
568                    "void FunctionTakesStringPtr(string* s);"
569                    "void run() {"
570                    "  string* s = GetStringPointer();"
571                    "  FunctionTakesStringPtr(GetStringPointer());"
572                    "  FunctionTakesStringPtr(s);"
573                    "}",
574                TempExpression));
575
576   EXPECT_TRUE(
577     notMatches("class no_dtor {};"
578                  "no_dtor GetObjByValue();"
579                  "void ConsumeObj(no_dtor param);"
580                  "void run() { ConsumeObj(GetObjByValue()); }",
581                TempExpression));
582 }
583
584 TEST(MaterializeTemporaryExpr, MatchesTemporary) {
585   std::string ClassString =
586     "class string { public: string(); int length(); }; ";
587
588   EXPECT_TRUE(
589     matches(ClassString +
590               "string GetStringByValue();"
591                 "void FunctionTakesString(string s);"
592                 "void run() { FunctionTakesString(GetStringByValue()); }",
593             materializeTemporaryExpr()));
594
595   EXPECT_TRUE(
596     notMatches(ClassString +
597                  "string* GetStringPointer(); "
598                    "void FunctionTakesStringPtr(string* s);"
599                    "void run() {"
600                    "  string* s = GetStringPointer();"
601                    "  FunctionTakesStringPtr(GetStringPointer());"
602                    "  FunctionTakesStringPtr(s);"
603                    "}",
604                materializeTemporaryExpr()));
605
606   EXPECT_TRUE(
607     matches(ClassString +
608                  "string GetStringByValue();"
609                    "void run() { int k = GetStringByValue().length(); }",
610                materializeTemporaryExpr()));
611
612   EXPECT_TRUE(
613     notMatches(ClassString +
614                  "string GetStringByValue();"
615                    "void run() { GetStringByValue(); }",
616                materializeTemporaryExpr()));
617 }
618
619 TEST(Matcher, NewExpression) {
620   StatementMatcher New = cxxNewExpr();
621
622   EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
623   EXPECT_TRUE(
624     matches("class X { public: X(); }; void x() { new X(); }", New));
625   EXPECT_TRUE(
626     matches("class X { public: X(int); }; void x() { new X(0); }", New));
627   EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
628 }
629
630 TEST(Matcher, DeleteExpression) {
631   EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
632                       cxxDeleteExpr()));
633 }
634
635 TEST(Matcher, DefaultArgument) {
636   StatementMatcher Arg = cxxDefaultArgExpr();
637
638   EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
639   EXPECT_TRUE(
640     matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
641   EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
642 }
643
644 TEST(Matcher, StringLiterals) {
645   StatementMatcher Literal = stringLiteral();
646   EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
647   // wide string
648   EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
649   // with escaped characters
650   EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
651   // no matching -- though the data type is the same, there is no string literal
652   EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
653 }
654
655 TEST(Matcher, CharacterLiterals) {
656   StatementMatcher CharLiteral = characterLiteral();
657   EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
658   // wide character
659   EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
660   // wide character, Hex encoded, NOT MATCHED!
661   EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
662   EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
663 }
664
665 TEST(Matcher, IntegerLiterals) {
666   StatementMatcher HasIntLiteral = integerLiteral();
667   EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
668   EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
669   EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
670   EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
671
672   // Non-matching cases (character literals, float and double)
673   EXPECT_TRUE(notMatches("int i = L'a';",
674                          HasIntLiteral));  // this is actually a character
675   // literal cast to int
676   EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
677   EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
678   EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
679
680   // Negative integers.
681   EXPECT_TRUE(
682       matches("int i = -10;",
683               unaryOperator(hasOperatorName("-"),
684                             hasUnaryOperand(integerLiteral(equals(10))))));
685 }
686
687 TEST(Matcher, FloatLiterals) {
688   StatementMatcher HasFloatLiteral = floatLiteral();
689   EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
690   EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
691   EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
692   EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
693   EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
694   EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
695   EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
696   EXPECT_TRUE(
697     matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
698
699   EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
700   EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
701   EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
702   EXPECT_TRUE(
703     notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
704 }
705
706 TEST(Matcher, NullPtrLiteral) {
707   EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
708 }
709
710 TEST(Matcher, GNUNullExpr) {
711   EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
712 }
713
714 TEST(Matcher, AtomicExpr) {
715   EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
716                       atomicExpr()));
717 }
718
719 TEST(Matcher, Initializers) {
720   const char *ToMatch = "void foo() { struct point { double x; double y; };"
721     "  struct point ptarray[10] = "
722     "      { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }";
723   EXPECT_TRUE(matchesConditionally(
724     ToMatch,
725     initListExpr(
726       has(
727         cxxConstructExpr(
728           requiresZeroInitialization())),
729       has(
730         initListExpr(
731           hasType(asString("struct point")),
732           has(floatLiteral(equals(1.0))),
733           has(implicitValueInitExpr(
734             hasType(asString("double")))))),
735       has(
736         initListExpr(
737           hasType(asString("struct point")),
738           has(floatLiteral(equals(2.0))),
739           has(floatLiteral(equals(1.0)))))
740     ), true, "-std=gnu++98"));
741
742   EXPECT_TRUE(matchesC99(ToMatch,
743                          initListExpr(
744                            hasSyntacticForm(
745                              initListExpr(
746                                has(
747                                  designatedInitExpr(
748                                    designatorCountIs(2),
749                                    has(floatLiteral(
750                                      equals(1.0))),
751                                    has(integerLiteral(
752                                      equals(2))))),
753                                has(
754                                  designatedInitExpr(
755                                    designatorCountIs(2),
756                                    has(floatLiteral(
757                                      equals(2.0))),
758                                    has(integerLiteral(
759                                      equals(2))))),
760                                has(
761                                  designatedInitExpr(
762                                    designatorCountIs(2),
763                                    has(floatLiteral(
764                                      equals(1.0))),
765                                    has(integerLiteral(
766                                      equals(0)))))
767                              )))));
768 }
769
770 TEST(Matcher, ParenListExpr) {
771   EXPECT_TRUE(
772     matches("template<typename T> class foo { void bar() { foo X(*this); } };"
773               "template class foo<int>;",
774             varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
775 }
776
777 TEST(Matcher, StmtExpr) {
778   EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
779                       varDecl(hasInitializer(stmtExpr()))));
780 }
781
782 TEST(Matcher, ImportPredefinedExpr) {
783   // __func__ expands as StringLiteral("foo")
784   EXPECT_TRUE(matches("void foo() { __func__; }",
785                       predefinedExpr(
786                         hasType(asString("const char [4]")),
787                         has(stringLiteral()))));
788 }
789
790 TEST(Matcher, AsmStatement) {
791   EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
792 }
793
794 TEST(Matcher, Conditions) {
795   StatementMatcher Condition =
796     ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
797
798   EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
799   EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
800   EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
801   EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
802   EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
803 }
804
805 TEST(Matcher, ConditionalOperator) {
806   StatementMatcher Conditional = conditionalOperator(
807     hasCondition(cxxBoolLiteral(equals(true))),
808     hasTrueExpression(cxxBoolLiteral(equals(false))));
809
810   EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
811   EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
812   EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
813
814   StatementMatcher ConditionalFalse = conditionalOperator(
815     hasFalseExpression(cxxBoolLiteral(equals(false))));
816
817   EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
818   EXPECT_TRUE(
819     notMatches("void x() { true ? false : true; }", ConditionalFalse));
820
821   EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
822   EXPECT_TRUE(
823     notMatches("void x() { true ? false : true; }", ConditionalFalse));
824 }
825
826 TEST(Matcher, BinaryConditionalOperator) {
827   StatementMatcher AlwaysOne = binaryConditionalOperator(
828     hasCondition(implicitCastExpr(
829       has(
830         opaqueValueExpr(
831           hasSourceExpression((integerLiteral(equals(1)))))))),
832     hasFalseExpression(integerLiteral(equals(0))));
833
834   EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne));
835
836   StatementMatcher FourNotFive = binaryConditionalOperator(
837     hasTrueExpression(opaqueValueExpr(
838       hasSourceExpression((integerLiteral(equals(4)))))),
839     hasFalseExpression(integerLiteral(equals(5))));
840
841   EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive));
842 }
843
844 TEST(ArraySubscriptMatchers, ArraySubscripts) {
845   EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
846                       arraySubscriptExpr()));
847   EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
848                          arraySubscriptExpr()));
849 }
850
851 TEST(For, FindsForLoops) {
852   EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
853   EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
854   EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
855                            "void f() { for (auto &a : as); }",
856                          forStmt()));
857 }
858
859 TEST(For, ReportsNoFalsePositives) {
860   EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
861   EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
862 }
863
864 TEST(CompoundStatement, HandlesSimpleCases) {
865   EXPECT_TRUE(notMatches("void f();", compoundStmt()));
866   EXPECT_TRUE(matches("void f() {}", compoundStmt()));
867   EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
868 }
869
870 TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
871   // It's not a compound statement just because there's "{}" in the source
872   // text. This is an AST search, not grep.
873   EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
874                          compoundStmt()));
875   EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
876                       compoundStmt()));
877 }
878
879 TEST(CastExpression, MatchesExplicitCasts) {
880   EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
881   EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
882   EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
883   EXPECT_TRUE(matches("char c = char(0);", castExpr()));
884 }
885 TEST(CastExpression, MatchesImplicitCasts) {
886   // This test creates an implicit cast from int to char.
887   EXPECT_TRUE(matches("char c = 0;", castExpr()));
888   // This test creates an implicit cast from lvalue to rvalue.
889   EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
890 }
891
892 TEST(CastExpression, DoesNotMatchNonCasts) {
893   EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
894   EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
895   EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
896   EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
897 }
898
899 TEST(ReinterpretCast, MatchesSimpleCase) {
900   EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
901                       cxxReinterpretCastExpr()));
902 }
903
904 TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
905   EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
906   EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
907                          cxxReinterpretCastExpr()));
908   EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
909                          cxxReinterpretCastExpr()));
910   EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
911                            "B b;"
912                            "D* p = dynamic_cast<D*>(&b);",
913                          cxxReinterpretCastExpr()));
914 }
915
916 TEST(FunctionalCast, MatchesSimpleCase) {
917   std::string foo_class = "class Foo { public: Foo(const char*); };";
918   EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
919                       cxxFunctionalCastExpr()));
920 }
921
922 TEST(FunctionalCast, DoesNotMatchOtherCasts) {
923   std::string FooClass = "class Foo { public: Foo(const char*); };";
924   EXPECT_TRUE(
925     notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
926                cxxFunctionalCastExpr()));
927   EXPECT_TRUE(
928     notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
929                cxxFunctionalCastExpr()));
930 }
931
932 TEST(DynamicCast, MatchesSimpleCase) {
933   EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
934                         "B b;"
935                         "D* p = dynamic_cast<D*>(&b);",
936                       cxxDynamicCastExpr()));
937 }
938
939 TEST(StaticCast, MatchesSimpleCase) {
940   EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
941                       cxxStaticCastExpr()));
942 }
943
944 TEST(StaticCast, DoesNotMatchOtherCasts) {
945   EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
946   EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
947                          cxxStaticCastExpr()));
948   EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
949                          cxxStaticCastExpr()));
950   EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
951                            "B b;"
952                            "D* p = dynamic_cast<D*>(&b);",
953                          cxxStaticCastExpr()));
954 }
955
956 TEST(CStyleCast, MatchesSimpleCase) {
957   EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
958 }
959
960 TEST(CStyleCast, DoesNotMatchOtherCasts) {
961   EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
962                            "char q, *r = const_cast<char*>(&q);"
963                            "void* s = reinterpret_cast<char*>(&s);"
964                            "struct B { virtual ~B() {} }; struct D : B {};"
965                            "B b;"
966                            "D* t = dynamic_cast<D*>(&b);",
967                          cStyleCastExpr()));
968 }
969
970 TEST(ImplicitCast, MatchesSimpleCase) {
971   // This test creates an implicit const cast.
972   EXPECT_TRUE(matches("int x = 0; const int y = x;",
973                       varDecl(hasInitializer(implicitCastExpr()))));
974   // This test creates an implicit cast from int to char.
975   EXPECT_TRUE(matches("char c = 0;",
976                       varDecl(hasInitializer(implicitCastExpr()))));
977   // This test creates an implicit array-to-pointer cast.
978   EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
979                       varDecl(hasInitializer(implicitCastExpr()))));
980 }
981
982 TEST(ImplicitCast, DoesNotMatchIncorrectly) {
983   // This test verifies that implicitCastExpr() matches exactly when implicit casts
984   // are present, and that it ignores explicit and paren casts.
985
986   // These two test cases have no casts.
987   EXPECT_TRUE(notMatches("int x = 0;",
988                          varDecl(hasInitializer(implicitCastExpr()))));
989   EXPECT_TRUE(notMatches("int x = 0, &y = x;",
990                          varDecl(hasInitializer(implicitCastExpr()))));
991
992   EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
993                          varDecl(hasInitializer(implicitCastExpr()))));
994   EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
995                          varDecl(hasInitializer(implicitCastExpr()))));
996
997   EXPECT_TRUE(notMatches("int x = (0);",
998                          varDecl(hasInitializer(implicitCastExpr()))));
999 }
1000
1001 TEST(Statement, DoesNotMatchDeclarations) {
1002   EXPECT_TRUE(notMatches("class X {};", stmt()));
1003 }
1004
1005 TEST(Statement, MatchesCompoundStatments) {
1006   EXPECT_TRUE(matches("void x() {}", stmt()));
1007 }
1008
1009 TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
1010   EXPECT_TRUE(notMatches("void x() {}", declStmt()));
1011 }
1012
1013 TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
1014   EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
1015 }
1016
1017 TEST(ExprWithCleanups, MatchesExprWithCleanups) {
1018   EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
1019                         "const Foo f = Foo();",
1020                       varDecl(hasInitializer(exprWithCleanups()))));
1021   EXPECT_FALSE(matches("struct Foo { }; Foo a;"
1022                        "const Foo f = a;",
1023                        varDecl(hasInitializer(exprWithCleanups()))));
1024 }
1025
1026 TEST(InitListExpression, MatchesInitListExpression) {
1027   EXPECT_TRUE(matches("int a[] = { 1, 2 };",
1028                       initListExpr(hasType(asString("int [2]")))));
1029   EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
1030                       initListExpr(hasType(recordDecl(hasName("B"))))));
1031   EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
1032                         "void f();"
1033                         "S s[1] = { &f };",
1034                       declRefExpr(to(functionDecl(hasName("f"))))));
1035   EXPECT_TRUE(
1036     matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
1037 }
1038
1039 TEST(CXXStdInitializerListExpression, MatchesCXXStdInitializerListExpression) {
1040   const std::string code = "namespace std {"
1041                            "template <typename> class initializer_list {"
1042                            "  public: initializer_list() noexcept {}"
1043                            "};"
1044                            "}"
1045                            "struct A {"
1046                            "  A(std::initializer_list<int>) {}"
1047                            "};";
1048   EXPECT_TRUE(matches(code + "A a{0};",
1049                       cxxConstructExpr(has(cxxStdInitializerListExpr()),
1050                                        hasDeclaration(cxxConstructorDecl(
1051                                            ofClass(hasName("A")))))));
1052   EXPECT_TRUE(matches(code + "A a = {0};",
1053                       cxxConstructExpr(has(cxxStdInitializerListExpr()),
1054                                        hasDeclaration(cxxConstructorDecl(
1055                                            ofClass(hasName("A")))))));
1056
1057   EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr()));
1058   EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };",
1059                          cxxStdInitializerListExpr()));
1060 }
1061
1062 TEST(UsingDeclaration, MatchesUsingDeclarations) {
1063   EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
1064                       usingDecl()));
1065 }
1066
1067 TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
1068   EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
1069                       usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
1070 }
1071
1072 TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
1073   EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
1074                       usingDirectiveDecl()));
1075   EXPECT_FALSE(
1076     matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
1077 }
1078
1079
1080 TEST(While, MatchesWhileLoops) {
1081   EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1082   EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
1083   EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
1084 }
1085
1086 TEST(Do, MatchesDoLoops) {
1087   EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
1088   EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
1089 }
1090
1091 TEST(Do, DoesNotMatchWhileLoops) {
1092   EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
1093 }
1094
1095 TEST(SwitchCase, MatchesCase) {
1096   EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1097   EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1098   EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1099   EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1100 }
1101
1102 TEST(SwitchCase, MatchesSwitch) {
1103   EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
1104   EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
1105   EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
1106   EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
1107 }
1108
1109 TEST(ExceptionHandling, SimpleCases) {
1110   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
1111   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
1112   EXPECT_TRUE(
1113     notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
1114   EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
1115                       cxxThrowExpr()));
1116   EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
1117                       cxxThrowExpr()));
1118   EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
1119                       cxxCatchStmt(isCatchAll())));
1120   EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
1121                          cxxCatchStmt(isCatchAll())));
1122   EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
1123                       varDecl(isExceptionVariable())));
1124   EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
1125                          varDecl(isExceptionVariable())));
1126 }
1127
1128 TEST(ParenExpression, SimpleCases) {
1129   EXPECT_TRUE(matches("int i = (3);", parenExpr()));
1130   EXPECT_TRUE(matches("int i = (3 + 7);", parenExpr()));
1131   EXPECT_TRUE(notMatches("int i = 3;", parenExpr()));
1132   EXPECT_TRUE(notMatches("int foo() { return 1; }; int a = foo();",
1133                          parenExpr()));
1134 }
1135
1136 TEST(TypeMatching, MatchesTypes) {
1137   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
1138 }
1139
1140 TEST(TypeMatching, MatchesConstantArrayTypes) {
1141   EXPECT_TRUE(matches("int a[2];", constantArrayType()));
1142   EXPECT_TRUE(notMatches(
1143     "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
1144     constantArrayType(hasElementType(builtinType()))));
1145
1146   EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
1147   EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
1148   EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
1149 }
1150
1151 TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
1152   EXPECT_TRUE(matches(
1153     "template <typename T, int Size> class array { T data[Size]; };",
1154     dependentSizedArrayType()));
1155   EXPECT_TRUE(notMatches(
1156     "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1157     dependentSizedArrayType()));
1158 }
1159
1160 TEST(TypeMatching, MatchesIncompleteArrayType) {
1161   EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
1162   EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
1163
1164   EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
1165                          incompleteArrayType()));
1166 }
1167
1168 TEST(TypeMatching, MatchesVariableArrayType) {
1169   EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
1170   EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
1171
1172   EXPECT_TRUE(matches(
1173     "void f(int b) { int a[b]; }",
1174     variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
1175       varDecl(hasName("b")))))))));
1176 }
1177
1178
1179 TEST(TypeMatching, MatchesAtomicTypes) {
1180   if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1181     llvm::Triple::Win32) {
1182     // FIXME: Make this work for MSVC.
1183     EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
1184
1185     EXPECT_TRUE(matches("_Atomic(int) i;",
1186                         atomicType(hasValueType(isInteger()))));
1187     EXPECT_TRUE(notMatches("_Atomic(float) f;",
1188                            atomicType(hasValueType(isInteger()))));
1189   }
1190 }
1191
1192 TEST(TypeMatching, MatchesAutoTypes) {
1193   EXPECT_TRUE(matches("auto i = 2;", autoType()));
1194   EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
1195                       autoType()));
1196
1197   EXPECT_TRUE(matches("auto i = 2;", varDecl(hasType(isInteger()))));
1198   EXPECT_TRUE(matches("struct X{}; auto x = X{};",
1199                       varDecl(hasType(recordDecl(hasName("X"))))));
1200
1201   // FIXME: Matching against the type-as-written can't work here, because the
1202   //        type as written was not deduced.
1203   //EXPECT_TRUE(matches("auto a = 1;",
1204   //                    autoType(hasDeducedType(isInteger()))));
1205   //EXPECT_TRUE(notMatches("auto b = 2.0;",
1206   //                       autoType(hasDeducedType(isInteger()))));
1207 }
1208
1209 TEST(TypeMatching, MatchesDeclTypes) {
1210   EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;", decltypeType()));
1211   EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;",
1212                       decltypeType(hasUnderlyingType(isInteger()))));
1213 }
1214
1215 TEST(TypeMatching, MatchesFunctionTypes) {
1216   EXPECT_TRUE(matches("int (*f)(int);", functionType()));
1217   EXPECT_TRUE(matches("void f(int i) {}", functionType()));
1218 }
1219
1220 TEST(TypeMatching, IgnoringParens) {
1221   EXPECT_TRUE(
1222       notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
1223   EXPECT_TRUE(matches("void (*fp)(void);",
1224                       pointerType(pointee(ignoringParens(functionType())))));
1225 }
1226
1227 TEST(TypeMatching, MatchesFunctionProtoTypes) {
1228   EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
1229   EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
1230   EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
1231   EXPECT_TRUE(notMatchesC("void f();", functionProtoType()));
1232   EXPECT_TRUE(
1233     matchesC("void f(void);", functionProtoType(parameterCountIs(0))));
1234 }
1235
1236 TEST(TypeMatching, MatchesParenType) {
1237   EXPECT_TRUE(
1238     matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
1239   EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
1240
1241   EXPECT_TRUE(matches(
1242     "int (*ptr_to_func)(int);",
1243     varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1244   EXPECT_TRUE(notMatches(
1245     "int (*ptr_to_array)[4];",
1246     varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1247 }
1248
1249 TEST(TypeMatching, PointerTypes) {
1250   // FIXME: Reactive when these tests can be more specific (not matching
1251   // implicit code on certain platforms), likely when we have hasDescendant for
1252   // Types/TypeLocs.
1253   //EXPECT_TRUE(matchAndVerifyResultTrue(
1254   //    "int* a;",
1255   //    pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
1256   //    llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1257   //EXPECT_TRUE(matchAndVerifyResultTrue(
1258   //    "int* a;",
1259   //    pointerTypeLoc().bind("loc"),
1260   //    llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1261   EXPECT_TRUE(matches(
1262     "int** a;",
1263     loc(pointerType(pointee(qualType())))));
1264   EXPECT_TRUE(matches(
1265     "int** a;",
1266     loc(pointerType(pointee(pointerType())))));
1267   EXPECT_TRUE(matches(
1268     "int* b; int* * const a = &b;",
1269     loc(qualType(isConstQualified(), pointerType()))));
1270
1271   std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
1272   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1273                                            hasType(blockPointerType()))));
1274   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
1275                                         hasType(memberPointerType()))));
1276   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1277                                            hasType(pointerType()))));
1278   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1279                                            hasType(referenceType()))));
1280   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1281                                            hasType(lValueReferenceType()))));
1282   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1283                                            hasType(rValueReferenceType()))));
1284
1285   Fragment = "int *ptr;";
1286   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1287                                            hasType(blockPointerType()))));
1288   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1289                                            hasType(memberPointerType()))));
1290   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
1291                                         hasType(pointerType()))));
1292   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1293                                            hasType(referenceType()))));
1294
1295   Fragment = "int a; int &ref = a;";
1296   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1297                                            hasType(blockPointerType()))));
1298   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1299                                            hasType(memberPointerType()))));
1300   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1301                                            hasType(pointerType()))));
1302   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1303                                         hasType(referenceType()))));
1304   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1305                                         hasType(lValueReferenceType()))));
1306   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1307                                            hasType(rValueReferenceType()))));
1308
1309   Fragment = "int &&ref = 2;";
1310   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1311                                            hasType(blockPointerType()))));
1312   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1313                                            hasType(memberPointerType()))));
1314   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1315                                            hasType(pointerType()))));
1316   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1317                                         hasType(referenceType()))));
1318   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1319                                            hasType(lValueReferenceType()))));
1320   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1321                                         hasType(rValueReferenceType()))));
1322 }
1323
1324 TEST(TypeMatching, AutoRefTypes) {
1325   std::string Fragment = "auto a = 1;"
1326     "auto b = a;"
1327     "auto &c = a;"
1328     "auto &&d = c;"
1329     "auto &&e = 2;";
1330   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
1331                                            hasType(referenceType()))));
1332   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
1333                                            hasType(referenceType()))));
1334   EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
1335                                         hasType(referenceType()))));
1336   EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
1337                                         hasType(lValueReferenceType()))));
1338   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
1339                                            hasType(rValueReferenceType()))));
1340   EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
1341                                         hasType(referenceType()))));
1342   EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
1343                                         hasType(lValueReferenceType()))));
1344   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
1345                                            hasType(rValueReferenceType()))));
1346   EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
1347                                         hasType(referenceType()))));
1348   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
1349                                            hasType(lValueReferenceType()))));
1350   EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
1351                                         hasType(rValueReferenceType()))));
1352 }
1353
1354 TEST(TypeMatching, MatchesEnumTypes) {
1355   EXPECT_TRUE(matches("enum Color { Green }; Color color;",
1356                       loc(enumType())));
1357   EXPECT_TRUE(matches("enum class Color { Green }; Color color;",
1358                       loc(enumType())));
1359 }
1360
1361 TEST(TypeMatching, MatchesPointersToConstTypes) {
1362   EXPECT_TRUE(matches("int b; int * const a = &b;",
1363                       loc(pointerType())));
1364   EXPECT_TRUE(matches("int b; int * const a = &b;",
1365                       loc(pointerType())));
1366   EXPECT_TRUE(matches(
1367     "int b; const int * a = &b;",
1368     loc(pointerType(pointee(builtinType())))));
1369   EXPECT_TRUE(matches(
1370     "int b; const int * a = &b;",
1371     pointerType(pointee(builtinType()))));
1372 }
1373
1374 TEST(TypeMatching, MatchesTypedefTypes) {
1375   EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
1376                                                      hasType(typedefType()))));
1377 }
1378
1379 TEST(TypeMatching, MatchesTemplateSpecializationType) {
1380   EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
1381                       templateSpecializationType()));
1382 }
1383
1384 TEST(TypeMatching, MatchesRecordType) {
1385   EXPECT_TRUE(matches("class C{}; C c;", recordType()));
1386   EXPECT_TRUE(matches("struct S{}; S s;",
1387                       recordType(hasDeclaration(recordDecl(hasName("S"))))));
1388   EXPECT_TRUE(notMatches("int i;",
1389                          recordType(hasDeclaration(recordDecl(hasName("S"))))));
1390 }
1391
1392 TEST(TypeMatching, MatchesElaboratedType) {
1393   EXPECT_TRUE(matches(
1394     "namespace N {"
1395       "  namespace M {"
1396       "    class D {};"
1397       "  }"
1398       "}"
1399       "N::M::D d;", elaboratedType()));
1400   EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
1401   EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
1402 }
1403
1404 TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
1405   const std::string code = "template <typename T>"
1406     "int F() {"
1407     "  return 1 + T();"
1408     "}"
1409     "int i = F<int>();";
1410   EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
1411     expr(hasType(substTemplateTypeParmType()))))));
1412   EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
1413     expr(hasType(substTemplateTypeParmType()))))));
1414 }
1415
1416 TEST(NNS, MatchesNestedNameSpecifiers) {
1417   EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
1418                       nestedNameSpecifier()));
1419   EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
1420                       nestedNameSpecifier()));
1421   EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
1422                       nestedNameSpecifier()));
1423   EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
1424                       nestedNameSpecifier()));
1425
1426   EXPECT_TRUE(matches(
1427     "struct A { static void f() {} }; void g() { A::f(); }",
1428     nestedNameSpecifier()));
1429   EXPECT_TRUE(notMatches(
1430     "struct A { static void f() {} }; void g(A* a) { a->f(); }",
1431     nestedNameSpecifier()));
1432 }
1433
1434 TEST(NullStatement, SimpleCases) {
1435   EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
1436   EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
1437 }
1438
1439 TEST(NS, Alias) {
1440   EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
1441                       namespaceAliasDecl(hasName("alias"))));
1442 }
1443
1444 TEST(NNS, MatchesTypes) {
1445   NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1446     specifiesType(hasDeclaration(recordDecl(hasName("A")))));
1447   EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
1448   EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
1449                       Matcher));
1450   EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
1451 }
1452
1453 TEST(NNS, MatchesNamespaceDecls) {
1454   NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1455     specifiesNamespace(hasName("ns")));
1456   EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
1457   EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
1458   EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
1459 }
1460
1461 TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
1462   EXPECT_TRUE(matches(
1463     "struct A { struct B { struct C {}; }; }; A::B::C c;",
1464     nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
1465   EXPECT_TRUE(matches(
1466     "struct A { struct B { struct C {}; }; }; A::B::C c;",
1467     nestedNameSpecifierLoc(hasPrefix(
1468       specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
1469   EXPECT_TRUE(matches(
1470     "namespace N { struct A { struct B { struct C {}; }; }; } N::A::B::C c;",
1471     nestedNameSpecifierLoc(hasPrefix(
1472       specifiesTypeLoc(loc(qualType(asString("struct N::A"))))))));
1473 }
1474
1475
1476 template <typename T>
1477 class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
1478 public:
1479   bool run(const BoundNodes *Nodes) override { return false; }
1480
1481   bool run(const BoundNodes *Nodes, ASTContext *Context) override {
1482     const T *Node = Nodes->getNodeAs<T>("");
1483     return verify(*Nodes, *Context, Node);
1484   }
1485
1486   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
1487     // Use the original typed pointer to verify we can pass pointers to subtypes
1488     // to equalsNode.
1489     const T *TypedNode = cast<T>(Node);
1490     return selectFirst<T>(
1491       "", match(stmt(hasParent(
1492         stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
1493                 *Node, Context)) != nullptr;
1494   }
1495   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
1496     // Use the original typed pointer to verify we can pass pointers to subtypes
1497     // to equalsNode.
1498     const T *TypedNode = cast<T>(Node);
1499     return selectFirst<T>(
1500       "", match(decl(hasParent(
1501         decl(has(decl(equalsNode(TypedNode)))).bind(""))),
1502                 *Node, Context)) != nullptr;
1503   }
1504   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
1505     // Use the original typed pointer to verify we can pass pointers to subtypes
1506     // to equalsNode.
1507     const T *TypedNode = cast<T>(Node);
1508     const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
1509     return selectFirst<T>(
1510       "", match(fieldDecl(hasParent(decl(has(fieldDecl(
1511         hasType(type(equalsNode(TypedNode)).bind(""))))))),
1512                 *Dec, Context)) != nullptr;
1513   }
1514 };
1515
1516 TEST(IsEqualTo, MatchesNodesByIdentity) {
1517   EXPECT_TRUE(matchAndVerifyResultTrue(
1518     "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
1519     llvm::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>()));
1520   EXPECT_TRUE(matchAndVerifyResultTrue(
1521     "void f() { if (true) if(true) {} }", ifStmt().bind(""),
1522     llvm::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>()));
1523   EXPECT_TRUE(matchAndVerifyResultTrue(
1524     "class X { class Y {} y; };",
1525     fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
1526     llvm::make_unique<VerifyAncestorHasChildIsEqual<Type>>()));
1527 }
1528
1529 TEST(TypedefDeclMatcher, Match) {
1530   EXPECT_TRUE(matches("typedef int typedefDeclTest;",
1531                       typedefDecl(hasName("typedefDeclTest"))));
1532   EXPECT_TRUE(notMatches("using typedefDeclTest2 = int;",
1533                          typedefDecl(hasName("typedefDeclTest2"))));
1534 }
1535
1536 TEST(TypeAliasDeclMatcher, Match) {
1537   EXPECT_TRUE(matches("using typeAliasTest2 = int;",
1538                       typeAliasDecl(hasName("typeAliasTest2"))));
1539   EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
1540                          typeAliasDecl(hasName("typeAliasTest"))));
1541 }
1542
1543 TEST(TypedefNameDeclMatcher, Match) {
1544   EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
1545                       typedefNameDecl(hasName("typedefNameDeclTest1"))));
1546   EXPECT_TRUE(matches("using typedefNameDeclTest2 = int;",
1547                       typedefNameDecl(hasName("typedefNameDeclTest2"))));
1548 }
1549
1550 TEST(TypeAliasTemplateDeclMatcher, Match) {
1551   std::string Code = R"(
1552     template <typename T>
1553     class X { T t; };
1554
1555     template <typename T>
1556     using typeAliasTemplateDecl = X<T>;
1557
1558     using typeAliasDecl = X<int>;
1559   )";
1560   EXPECT_TRUE(
1561       matches(Code, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl"))));
1562   EXPECT_TRUE(
1563       notMatches(Code, typeAliasTemplateDecl(hasName("typeAliasDecl"))));
1564 }
1565
1566 TEST(ObjCMessageExprMatcher, SimpleExprs) {
1567   // don't find ObjCMessageExpr where none are present
1568   EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
1569
1570   std::string Objc1String =
1571     "@interface Str "
1572       " - (Str *)uppercaseString;"
1573       "@end "
1574       "@interface foo "
1575       "- (void)contents;"
1576       "- (void)meth:(Str *)text;"
1577       "@end "
1578       " "
1579       "@implementation foo "
1580       "- (void) meth:(Str *)text { "
1581       "  [self contents];"
1582       "  Str *up = [text uppercaseString];"
1583       "} "
1584       "@end ";
1585   EXPECT_TRUE(matchesObjC(
1586     Objc1String,
1587     objcMessageExpr(anything())));
1588   EXPECT_TRUE(matchesObjC(Objc1String,
1589                           objcMessageExpr(hasAnySelector({
1590                                           "contents", "meth:"}))
1591
1592                          ));
1593   EXPECT_TRUE(matchesObjC(
1594     Objc1String,
1595     objcMessageExpr(hasSelector("contents"))));
1596   EXPECT_TRUE(matchesObjC(
1597     Objc1String,
1598     objcMessageExpr(hasAnySelector("contents", "contentsA"))));
1599   EXPECT_FALSE(matchesObjC(
1600     Objc1String,
1601     objcMessageExpr(hasAnySelector("contentsB", "contentsC"))));
1602   EXPECT_TRUE(matchesObjC(
1603     Objc1String,
1604     objcMessageExpr(matchesSelector("cont*"))));
1605   EXPECT_FALSE(matchesObjC(
1606     Objc1String,
1607     objcMessageExpr(matchesSelector("?cont*"))));
1608   EXPECT_TRUE(notMatchesObjC(
1609     Objc1String,
1610     objcMessageExpr(hasSelector("contents"), hasNullSelector())));
1611   EXPECT_TRUE(matchesObjC(
1612     Objc1String,
1613     objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
1614   EXPECT_TRUE(matchesObjC(
1615     Objc1String,
1616     objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
1617   EXPECT_TRUE(matchesObjC(
1618     Objc1String,
1619     objcMessageExpr(matchesSelector("uppercase*"),
1620                     argumentCountIs(0)
1621     )));
1622 }
1623
1624 TEST(ObjCDeclMatcher, CoreDecls) {
1625   std::string ObjCString =
1626     "@protocol Proto "
1627     "- (void)protoDidThing; "
1628     "@end "
1629     "@interface Thing "
1630     "@property int enabled; "
1631     "@end "
1632     "@interface Thing (ABC) "
1633     "- (void)abc_doThing; "
1634     "@end "
1635     "@implementation Thing "
1636     "{ id _ivar; } "
1637     "- (void)anything {} "
1638     "@end "
1639     "@implementation Thing (ABC) "
1640     "- (void)abc_doThing {} "
1641     "@end "
1642     ;
1643
1644   EXPECT_TRUE(matchesObjC(
1645     ObjCString,
1646     objcProtocolDecl(hasName("Proto"))));
1647   EXPECT_TRUE(matchesObjC(
1648     ObjCString,
1649     objcImplementationDecl(hasName("Thing"))));
1650   EXPECT_TRUE(matchesObjC(
1651     ObjCString,
1652     objcCategoryDecl(hasName("ABC"))));
1653   EXPECT_TRUE(matchesObjC(
1654     ObjCString,
1655     objcCategoryImplDecl(hasName("ABC"))));
1656   EXPECT_TRUE(matchesObjC(
1657     ObjCString,
1658     objcMethodDecl(hasName("protoDidThing"))));
1659   EXPECT_TRUE(matchesObjC(
1660     ObjCString,
1661     objcMethodDecl(hasName("abc_doThing"))));
1662   EXPECT_TRUE(matchesObjC(
1663     ObjCString,
1664     objcMethodDecl(hasName("anything"))));
1665   EXPECT_TRUE(matchesObjC(
1666     ObjCString,
1667     objcIvarDecl(hasName("_ivar"))));
1668   EXPECT_TRUE(matchesObjC(
1669     ObjCString,
1670     objcPropertyDecl(hasName("enabled"))));
1671 }
1672
1673 TEST(ObjCStmtMatcher, ExceptionStmts) {
1674   std::string ObjCString =
1675     "void f(id obj) {"
1676     "  @try {"
1677     "    @throw obj;"
1678     "  } @catch (...) {"
1679     "  } @finally {}"
1680     "}";
1681
1682   EXPECT_TRUE(matchesObjC(
1683     ObjCString,
1684     objcTryStmt()));
1685   EXPECT_TRUE(matchesObjC(
1686     ObjCString,
1687     objcThrowStmt()));
1688   EXPECT_TRUE(matchesObjC(
1689     ObjCString,
1690     objcCatchStmt()));
1691   EXPECT_TRUE(matchesObjC(
1692     ObjCString,
1693     objcFinallyStmt()));
1694 }
1695
1696 TEST(ObjCAutoreleaseMatcher, AutoreleasePool) {
1697   std::string ObjCString =
1698     "void f() {"
1699     "@autoreleasepool {"
1700     "  int x = 1;"
1701     "}"
1702     "}";
1703   EXPECT_TRUE(matchesObjC(ObjCString, autoreleasePoolStmt()));
1704   std::string ObjCStringNoPool = "void f() { int x = 1; }";
1705   EXPECT_FALSE(matchesObjC(ObjCStringNoPool, autoreleasePoolStmt()));
1706 }
1707
1708 } // namespace ast_matchers
1709 } // namespace clang