1//===- unittest/Tooling/ASTMatchersTest.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
19namespace clang {
20namespace ast_matchers {
21
22#if GTEST_HAS_DEATH_TEST
23TEST(HasNameDeathTest, DiesOnEmptyName) {
24  ASSERT_DEBUG_DEATH({
25    DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
26    EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27  }, "");
28}
29
30TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31  ASSERT_DEBUG_DEATH({
32      DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
33      EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34    }, "");
35}
36
37TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38  ASSERT_DEBUG_DEATH({
39    DeclarationMatcher IsDerivedFromEmpty = cxxRecordDecl(isDerivedFrom(""));
40    EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41  }, "");
42}
43#endif
44
45TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46  MatchFinder Finder;
47  EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48  EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49  EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50                                       nullptr));
51
52  // Do not accept non-toplevel matchers.
53  EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54  EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55  EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
56}
57
58TEST(Decl, MatchesDeclarations) {
59  EXPECT_TRUE(notMatches("", decl(usingDecl())));
60  EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
61                      decl(usingDecl())));
62}
63
64TEST(NameableDeclaration, MatchesVariousDecls) {
65  DeclarationMatcher NamedX = namedDecl(hasName("X"));
66  EXPECT_TRUE(matches("typedef int X;", NamedX));
67  EXPECT_TRUE(matches("int X;", NamedX));
68  EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
69  EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
70  EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
71  EXPECT_TRUE(matches("namespace X { }", NamedX));
72  EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
73
74  EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
77TEST(NameableDeclaration, REMatchesVariousDecls) {
78  DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
79  EXPECT_TRUE(matches("typedef int Xa;", NamedX));
80  EXPECT_TRUE(matches("int Xb;", NamedX));
81  EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
82  EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
83  EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
84  EXPECT_TRUE(matches("namespace Xij { }", NamedX));
85  EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
86
87  EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
88
89  DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
90  EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
91  EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
92
93  DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
94  EXPECT_TRUE(matches("int abc;", Abc));
95  EXPECT_TRUE(matches("int aFOObBARc;", Abc));
96  EXPECT_TRUE(notMatches("int cab;", Abc));
97  EXPECT_TRUE(matches("int cabc;", Abc));
98
99  DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
100  EXPECT_TRUE(matches("int k;", StartsWithK));
101  EXPECT_TRUE(matches("int kAbc;", StartsWithK));
102  EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
103  EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
104  EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
105}
106
107TEST(DeclarationMatcher, MatchClass) {
108  DeclarationMatcher ClassMatcher(recordDecl());
109  llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110  if (Triple.getOS() != llvm::Triple::Win32 ||
111      Triple.getEnvironment() != llvm::Triple::MSVC)
112    EXPECT_FALSE(matches("", ClassMatcher));
113  else
114    // Matches class type_info.
115    EXPECT_TRUE(matches("", ClassMatcher));
116
117  DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
118  EXPECT_TRUE(matches("class X;", ClassX));
119  EXPECT_TRUE(matches("class X {};", ClassX));
120  EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
121  EXPECT_TRUE(notMatches("", ClassX));
122}
123
124TEST(DeclarationMatcher, ClassIsDerived) {
125  DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
126
127  EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
128  EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129  EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
130  EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131  EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
133  DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
134
135  EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
136  EXPECT_TRUE(matches("class X {};", IsAX));
137  EXPECT_TRUE(matches("class X;", IsAX));
138  EXPECT_TRUE(notMatches("class Y;", IsAX));
139  EXPECT_TRUE(notMatches("", IsAX));
140
141  DeclarationMatcher ZIsDerivedFromX =
142      cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
143  EXPECT_TRUE(
144      matches("class X {}; class Y : public X {}; class Z : public Y {};",
145              ZIsDerivedFromX));
146  EXPECT_TRUE(
147      matches("class X {};"
148              "template<class T> class Y : public X {};"
149              "class Z : public Y<int> {};", ZIsDerivedFromX));
150  EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
151                      ZIsDerivedFromX));
152  EXPECT_TRUE(
153      matches("template<class T> class X {}; "
154              "template<class T> class Z : public X<T> {};",
155              ZIsDerivedFromX));
156  EXPECT_TRUE(
157      matches("template<class T, class U=T> class X {}; "
158              "template<class T> class Z : public X<T> {};",
159              ZIsDerivedFromX));
160  EXPECT_TRUE(
161      notMatches("template<class X> class A { class Z : public X {}; };",
162                 ZIsDerivedFromX));
163  EXPECT_TRUE(
164      matches("template<class X> class A { public: class Z : public X {}; }; "
165              "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
166  EXPECT_TRUE(
167      matches("template <class T> class X {}; "
168              "template<class Y> class A { class Z : public X<Y> {}; };",
169              ZIsDerivedFromX));
170  EXPECT_TRUE(
171      notMatches("template<template<class T> class X> class A { "
172                 "  class Z : public X<int> {}; };", ZIsDerivedFromX));
173  EXPECT_TRUE(
174      matches("template<template<class T> class X> class A { "
175              "  public: class Z : public X<int> {}; }; "
176              "template<class T> class X {}; void y() { A<X>::Z z; }",
177              ZIsDerivedFromX));
178  EXPECT_TRUE(
179      notMatches("template<class X> class A { class Z : public X::D {}; };",
180                 ZIsDerivedFromX));
181  EXPECT_TRUE(
182      matches("template<class X> class A { public: "
183              "  class Z : public X::D {}; }; "
184              "class Y { public: class X {}; typedef X D; }; "
185              "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
186  EXPECT_TRUE(
187      matches("class X {}; typedef X Y; class Z : public Y {};",
188              ZIsDerivedFromX));
189  EXPECT_TRUE(
190      matches("template<class T> class Y { typedef typename T::U X; "
191              "  class Z : public X {}; };", ZIsDerivedFromX));
192  EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
193                      ZIsDerivedFromX));
194  EXPECT_TRUE(
195      notMatches("template<class T> class X {}; "
196                "template<class T> class A { class Z : public X<T>::D {}; };",
197                ZIsDerivedFromX));
198  EXPECT_TRUE(
199      matches("template<class T> class X { public: typedef X<T> D; }; "
200              "template<class T> class A { public: "
201              "  class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
202              ZIsDerivedFromX));
203  EXPECT_TRUE(
204      notMatches("template<class X> class A { class Z : public X::D::E {}; };",
205                 ZIsDerivedFromX));
206  EXPECT_TRUE(
207      matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
208              ZIsDerivedFromX));
209  EXPECT_TRUE(
210      matches("class X {}; class Y : public X {}; "
211              "typedef Y V; typedef V W; class Z : public W {};",
212              ZIsDerivedFromX));
213  EXPECT_TRUE(
214      matches("template<class T, class U> class X {}; "
215              "template<class T> class A { class Z : public X<T, int> {}; };",
216              ZIsDerivedFromX));
217  EXPECT_TRUE(
218      notMatches("template<class X> class D { typedef X A; typedef A B; "
219                 "  typedef B C; class Z : public C {}; };",
220                 ZIsDerivedFromX));
221  EXPECT_TRUE(
222      matches("class X {}; typedef X A; typedef A B; "
223              "class Z : public B {};", ZIsDerivedFromX));
224  EXPECT_TRUE(
225      matches("class X {}; typedef X A; typedef A B; typedef B C; "
226              "class Z : public C {};", ZIsDerivedFromX));
227  EXPECT_TRUE(
228      matches("class U {}; typedef U X; typedef X V; "
229              "class Z : public V {};", ZIsDerivedFromX));
230  EXPECT_TRUE(
231      matches("class Base {}; typedef Base X; "
232              "class Z : public Base {};", ZIsDerivedFromX));
233  EXPECT_TRUE(
234      matches("class Base {}; typedef Base Base2; typedef Base2 X; "
235              "class Z : public Base {};", ZIsDerivedFromX));
236  EXPECT_TRUE(
237      notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
238                 "class Z : public Base {};", ZIsDerivedFromX));
239  EXPECT_TRUE(
240      matches("class A {}; typedef A X; typedef A Y; "
241              "class Z : public Y {};", ZIsDerivedFromX));
242  EXPECT_TRUE(
243      notMatches("template <typename T> class Z;"
244                 "template <> class Z<void> {};"
245                 "template <typename T> class Z : public Z<void> {};",
246                 IsDerivedFromX));
247  EXPECT_TRUE(
248      matches("template <typename T> class X;"
249              "template <> class X<void> {};"
250              "template <typename T> class X : public X<void> {};",
251              IsDerivedFromX));
252  EXPECT_TRUE(matches(
253      "class X {};"
254      "template <typename T> class Z;"
255      "template <> class Z<void> {};"
256      "template <typename T> class Z : public Z<void>, public X {};",
257      ZIsDerivedFromX));
258  EXPECT_TRUE(
259      notMatches("template<int> struct X;"
260                 "template<int i> struct X : public X<i-1> {};",
261                 cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
262  EXPECT_TRUE(matches(
263      "struct A {};"
264      "template<int> struct X;"
265      "template<int i> struct X : public X<i-1> {};"
266      "template<> struct X<0> : public A {};"
267      "struct B : public X<42> {};",
268      cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
269
270  // FIXME: Once we have better matchers for template type matching,
271  // get rid of the Variable(...) matching and match the right template
272  // declarations directly.
273  const char *RecursiveTemplateOneParameter =
274      "class Base1 {}; class Base2 {};"
275      "template <typename T> class Z;"
276      "template <> class Z<void> : public Base1 {};"
277      "template <> class Z<int> : public Base2 {};"
278      "template <> class Z<float> : public Z<void> {};"
279      "template <> class Z<double> : public Z<int> {};"
280      "template <typename T> class Z : public Z<float>, public Z<double> {};"
281      "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
282  EXPECT_TRUE(matches(
283      RecursiveTemplateOneParameter,
284      varDecl(hasName("z_float"),
285              hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
286  EXPECT_TRUE(notMatches(
287      RecursiveTemplateOneParameter,
288      varDecl(hasName("z_float"),
289              hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
290  EXPECT_TRUE(matches(
291      RecursiveTemplateOneParameter,
292      varDecl(hasName("z_char"),
293              hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
294                                                isDerivedFrom("Base2")))))));
295
296  const char *RecursiveTemplateTwoParameters =
297      "class Base1 {}; class Base2 {};"
298      "template <typename T1, typename T2> class Z;"
299      "template <typename T> class Z<void, T> : public Base1 {};"
300      "template <typename T> class Z<int, T> : public Base2 {};"
301      "template <typename T> class Z<float, T> : public Z<void, T> {};"
302      "template <typename T> class Z<double, T> : public Z<int, T> {};"
303      "template <typename T1, typename T2> class Z : "
304      "    public Z<float, T2>, public Z<double, T2> {};"
305      "void f() { Z<float, void> z_float; Z<double, void> z_double; "
306      "           Z<char, void> z_char; }";
307  EXPECT_TRUE(matches(
308      RecursiveTemplateTwoParameters,
309      varDecl(hasName("z_float"),
310              hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
311  EXPECT_TRUE(notMatches(
312      RecursiveTemplateTwoParameters,
313      varDecl(hasName("z_float"),
314              hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
315  EXPECT_TRUE(matches(
316      RecursiveTemplateTwoParameters,
317      varDecl(hasName("z_char"),
318              hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
319                                                isDerivedFrom("Base2")))))));
320  EXPECT_TRUE(matches(
321      "namespace ns { class X {}; class Y : public X {}; }",
322      cxxRecordDecl(isDerivedFrom("::ns::X"))));
323  EXPECT_TRUE(notMatches(
324      "class X {}; class Y : public X {};",
325      cxxRecordDecl(isDerivedFrom("::ns::X"))));
326
327  EXPECT_TRUE(matches(
328      "class X {}; class Y : public X {};",
329    cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
330
331  EXPECT_TRUE(matches(
332      "template<typename T> class X {};"
333      "template<typename T> using Z = X<T>;"
334      "template <typename T> class Y : Z<T> {};",
335    cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
336}
337
338TEST(DeclarationMatcher, hasMethod) {
339  EXPECT_TRUE(matches("class A { void func(); };",
340                      cxxRecordDecl(hasMethod(hasName("func")))));
341  EXPECT_TRUE(notMatches("class A { void func(); };",
342                         cxxRecordDecl(hasMethod(isPublic()))));
343}
344
345TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
346  EXPECT_TRUE(matches(
347     "template <typename T> struct A {"
348     "  template <typename T2> struct F {};"
349     "};"
350     "template <typename T> struct B : A<T>::template F<T> {};"
351     "B<int> b;",
352    cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
353}
354
355TEST(DeclarationMatcher, hasDeclContext) {
356  EXPECT_TRUE(matches(
357      "namespace N {"
358      "  namespace M {"
359      "    class D {};"
360      "  }"
361      "}",
362      recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
363  EXPECT_TRUE(notMatches(
364      "namespace N {"
365      "  namespace M {"
366      "    class D {};"
367      "  }"
368      "}",
369      recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
370
371  EXPECT_TRUE(matches("namespace {"
372                      "  namespace M {"
373                      "    class D {};"
374                      "  }"
375                      "}",
376                      recordDecl(hasDeclContext(namespaceDecl(
377                          hasName("M"), hasDeclContext(namespaceDecl()))))));
378
379  EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
380}
381
382TEST(DeclarationMatcher, translationUnitDecl) {
383  const std::string Code = "int MyVar1;\n"
384                           "namespace NameSpace {\n"
385                           "int MyVar2;\n"
386                           "}  // namespace NameSpace\n";
387  EXPECT_TRUE(matches(
388      Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
389  EXPECT_FALSE(matches(
390      Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
391  EXPECT_TRUE(matches(
392      Code,
393      varDecl(hasName("MyVar2"),
394              hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
395}
396
397TEST(DeclarationMatcher, LinkageSpecification) {
398  EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
399  EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
400}
401
402TEST(ClassTemplate, DoesNotMatchClass) {
403  DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
404  EXPECT_TRUE(notMatches("class X;", ClassX));
405  EXPECT_TRUE(notMatches("class X {};", ClassX));
406}
407
408TEST(ClassTemplate, MatchesClassTemplate) {
409  DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
410  EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
411  EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
412}
413
414TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
415  EXPECT_TRUE(notMatches("template<typename T> class X { };"
416                         "template<> class X<int> { int a; };",
417              classTemplateDecl(hasName("X"),
418                                hasDescendant(fieldDecl(hasName("a"))))));
419}
420
421TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
422  EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
423                         "template<typename T> class X<T, int> { int a; };",
424              classTemplateDecl(hasName("X"),
425                                hasDescendant(fieldDecl(hasName("a"))))));
426}
427
428TEST(AllOf, AllOverloadsWork) {
429  const char Program[] =
430      "struct T { };"
431      "int f(int, T*, int, int);"
432      "void g(int x) { T t; f(x, &t, 3, 4); }";
433  EXPECT_TRUE(matches(Program,
434      callExpr(allOf(callee(functionDecl(hasName("f"))),
435                     hasArgument(0, declRefExpr(to(varDecl())))))));
436  EXPECT_TRUE(matches(Program,
437      callExpr(allOf(callee(functionDecl(hasName("f"))),
438                     hasArgument(0, declRefExpr(to(varDecl()))),
439                     hasArgument(1, hasType(pointsTo(
440                                        recordDecl(hasName("T")))))))));
441  EXPECT_TRUE(matches(Program,
442      callExpr(allOf(callee(functionDecl(hasName("f"))),
443                     hasArgument(0, declRefExpr(to(varDecl()))),
444                     hasArgument(1, hasType(pointsTo(
445                                        recordDecl(hasName("T"))))),
446                     hasArgument(2, integerLiteral(equals(3)))))));
447  EXPECT_TRUE(matches(Program,
448      callExpr(allOf(callee(functionDecl(hasName("f"))),
449                     hasArgument(0, declRefExpr(to(varDecl()))),
450                     hasArgument(1, hasType(pointsTo(
451                                        recordDecl(hasName("T"))))),
452                     hasArgument(2, integerLiteral(equals(3))),
453                     hasArgument(3, integerLiteral(equals(4)))))));
454}
455
456TEST(ConstructVariadic, MismatchedTypes_Regression) {
457  EXPECT_TRUE(
458      matches("const int a = 0;",
459              internal::DynTypedMatcher::constructVariadic(
460                  internal::DynTypedMatcher::VO_AnyOf,
461                  ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>(),
462                  {isConstQualified(), arrayType()})
463                  .convertTo<QualType>()));
464}
465
466TEST(DeclarationMatcher, MatchAnyOf) {
467  DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
468      anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
469  EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
470  EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
471  EXPECT_TRUE(
472      notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
473  EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
474
475  DeclarationMatcher XOrYOrZOrU =
476      recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
477  EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
478  EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
479
480  DeclarationMatcher XOrYOrZOrUOrV =
481      recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
482                       hasName("V")));
483  EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
484  EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
485  EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
486  EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
487  EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
488  EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
489
490  StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
491  EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
492  EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
493  EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
494
495  EXPECT_TRUE(
496      matches("void f() try { } catch (int) { } catch (...) { }",
497              cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
498}
499
500TEST(DeclarationMatcher, MatchHas) {
501  DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
502  EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
503  EXPECT_TRUE(matches("class X {};", HasClassX));
504
505  DeclarationMatcher YHasClassX =
506      recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
507  EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
508  EXPECT_TRUE(notMatches("class X {};", YHasClassX));
509  EXPECT_TRUE(
510      notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
511}
512
513TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
514  DeclarationMatcher Recursive =
515    recordDecl(
516      has(recordDecl(
517        has(recordDecl(hasName("X"))),
518        has(recordDecl(hasName("Y"))),
519        hasName("Z"))),
520      has(recordDecl(
521        has(recordDecl(hasName("A"))),
522        has(recordDecl(hasName("B"))),
523        hasName("C"))),
524      hasName("F"));
525
526  EXPECT_TRUE(matches(
527      "class F {"
528      "  class Z {"
529      "    class X {};"
530      "    class Y {};"
531      "  };"
532      "  class C {"
533      "    class A {};"
534      "    class B {};"
535      "  };"
536      "};", Recursive));
537
538  EXPECT_TRUE(matches(
539      "class F {"
540      "  class Z {"
541      "    class A {};"
542      "    class X {};"
543      "    class Y {};"
544      "  };"
545      "  class C {"
546      "    class X {};"
547      "    class A {};"
548      "    class B {};"
549      "  };"
550      "};", Recursive));
551
552  EXPECT_TRUE(matches(
553      "class O1 {"
554      "  class O2 {"
555      "    class F {"
556      "      class Z {"
557      "        class A {};"
558      "        class X {};"
559      "        class Y {};"
560      "      };"
561      "      class C {"
562      "        class X {};"
563      "        class A {};"
564      "        class B {};"
565      "      };"
566      "    };"
567      "  };"
568      "};", Recursive));
569}
570
571TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
572  DeclarationMatcher Recursive =
573      recordDecl(
574          anyOf(
575              has(recordDecl(
576                  anyOf(
577                      has(recordDecl(
578                          hasName("X"))),
579                      has(recordDecl(
580                          hasName("Y"))),
581                      hasName("Z")))),
582              has(recordDecl(
583                  anyOf(
584                      hasName("C"),
585                      has(recordDecl(
586                          hasName("A"))),
587                      has(recordDecl(
588                          hasName("B")))))),
589              hasName("F")));
590
591  EXPECT_TRUE(matches("class F {};", Recursive));
592  EXPECT_TRUE(matches("class Z {};", Recursive));
593  EXPECT_TRUE(matches("class C {};", Recursive));
594  EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
595  EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
596  EXPECT_TRUE(
597      matches("class O1 { class O2 {"
598              "  class M { class N { class B {}; }; }; "
599              "}; };", Recursive));
600}
601
602TEST(DeclarationMatcher, MatchNot) {
603  DeclarationMatcher NotClassX =
604    cxxRecordDecl(
605          isDerivedFrom("Y"),
606          unless(hasName("X")));
607  EXPECT_TRUE(notMatches("", NotClassX));
608  EXPECT_TRUE(notMatches("class Y {};", NotClassX));
609  EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
610  EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
611  EXPECT_TRUE(
612      notMatches("class Y {}; class Z {}; class X : public Y {};",
613                 NotClassX));
614
615  DeclarationMatcher ClassXHasNotClassY =
616      recordDecl(
617          hasName("X"),
618          has(recordDecl(hasName("Z"))),
619          unless(
620              has(recordDecl(hasName("Y")))));
621  EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
622  EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
623                         ClassXHasNotClassY));
624
625  DeclarationMatcher NamedNotRecord =
626      namedDecl(hasName("Foo"), unless(recordDecl()));
627  EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
628  EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
629}
630
631TEST(DeclarationMatcher, HasDescendant) {
632  DeclarationMatcher ZDescendantClassX =
633      recordDecl(
634          hasDescendant(recordDecl(hasName("X"))),
635          hasName("Z"));
636  EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
637  EXPECT_TRUE(
638      matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
639  EXPECT_TRUE(
640      matches("class Z { class A { class Y { class X {}; }; }; };",
641              ZDescendantClassX));
642  EXPECT_TRUE(
643      matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
644              ZDescendantClassX));
645  EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
646
647  DeclarationMatcher ZDescendantClassXHasClassY =
648      recordDecl(
649          hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
650                              hasName("X"))),
651          hasName("Z"));
652  EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
653              ZDescendantClassXHasClassY));
654  EXPECT_TRUE(
655      matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
656              ZDescendantClassXHasClassY));
657  EXPECT_TRUE(notMatches(
658      "class Z {"
659      "  class A {"
660      "    class B {"
661      "      class X {"
662      "        class C {"
663      "          class Y {};"
664      "        };"
665      "      };"
666      "    }; "
667      "  };"
668      "};", ZDescendantClassXHasClassY));
669
670  DeclarationMatcher ZDescendantClassXDescendantClassY =
671      recordDecl(
672          hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
673                                   hasName("X"))),
674          hasName("Z"));
675  EXPECT_TRUE(
676      matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
677              ZDescendantClassXDescendantClassY));
678  EXPECT_TRUE(matches(
679      "class Z {"
680      "  class A {"
681      "    class X {"
682      "      class B {"
683      "        class Y {};"
684      "      };"
685      "      class Y {};"
686      "    };"
687      "  };"
688      "};", ZDescendantClassXDescendantClassY));
689}
690
691TEST(DeclarationMatcher, HasDescendantMemoization) {
692  DeclarationMatcher CannotMemoize =
693      decl(hasDescendant(typeLoc().bind("x")), has(decl()));
694  EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
695}
696
697TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
698  auto Name = hasName("i");
699  auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
700  auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
701  // Matching VD first should not make a cache hit for RD.
702  EXPECT_TRUE(notMatches("void f() { int i; }",
703                         decl(hasDescendant(VD), hasDescendant(RD))));
704  EXPECT_TRUE(notMatches("void f() { int i; }",
705                         decl(hasDescendant(RD), hasDescendant(VD))));
706  // Not matching RD first should not make a cache hit for VD either.
707  EXPECT_TRUE(matches("void f() { int i; }",
708                      decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
709}
710
711TEST(DeclarationMatcher, HasAttr) {
712  EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
713                      decl(hasAttr(clang::attr::WarnUnused))));
714  EXPECT_FALSE(matches("struct X {};",
715                       decl(hasAttr(clang::attr::WarnUnused))));
716}
717
718TEST(DeclarationMatcher, MatchCudaDecl) {
719  EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
720                              "void g() { f<<<1, 2>>>(); }",
721                              cudaKernelCallExpr()));
722  EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
723                              hasAttr(clang::attr::CUDADevice)));
724  EXPECT_TRUE(notMatchesWithCuda("void f() {}",
725                                 cudaKernelCallExpr()));
726  EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
727                                  hasAttr(clang::attr::CUDAGlobal)));
728}
729
730// Implements a run method that returns whether BoundNodes contains a
731// Decl bound to Id that can be dynamically cast to T.
732// Optionally checks that the check succeeded a specific number of times.
733template <typename T>
734class VerifyIdIsBoundTo : public BoundNodesCallback {
735public:
736  // Create an object that checks that a node of type \c T was bound to \c Id.
737  // Does not check for a certain number of matches.
738  explicit VerifyIdIsBoundTo(llvm::StringRef Id)
739    : Id(Id), ExpectedCount(-1), Count(0) {}
740
741  // Create an object that checks that a node of type \c T was bound to \c Id.
742  // Checks that there were exactly \c ExpectedCount matches.
743  VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
744    : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
745
746  // Create an object that checks that a node of type \c T was bound to \c Id.
747  // Checks that there was exactly one match with the name \c ExpectedName.
748  // Note that \c T must be a NamedDecl for this to work.
749  VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
750                    int ExpectedCount = 1)
751      : Id(Id), ExpectedCount(ExpectedCount), Count(0),
752        ExpectedName(ExpectedName) {}
753
754  void onEndOfTranslationUnit() override {
755    if (ExpectedCount != -1)
756      EXPECT_EQ(ExpectedCount, Count);
757    if (!ExpectedName.empty())
758      EXPECT_EQ(ExpectedName, Name);
759    Count = 0;
760    Name.clear();
761  }
762
763  ~VerifyIdIsBoundTo() override {
764    EXPECT_EQ(0, Count);
765    EXPECT_EQ("", Name);
766  }
767
768  bool run(const BoundNodes *Nodes) override {
769    const BoundNodes::IDToNodeMap &M = Nodes->getMap();
770    if (Nodes->getNodeAs<T>(Id)) {
771      ++Count;
772      if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
773        Name = Named->getNameAsString();
774      } else if (const NestedNameSpecifier *NNS =
775                 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
776        llvm::raw_string_ostream OS(Name);
777        NNS->print(OS, PrintingPolicy(LangOptions()));
778      }
779      BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
780      EXPECT_NE(M.end(), I);
781      if (I != M.end())
782        EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
783      return true;
784    }
785    EXPECT_TRUE(M.count(Id) == 0 ||
786                M.find(Id)->second.template get<T>() == nullptr);
787    return false;
788  }
789
790  bool run(const BoundNodes *Nodes, ASTContext *Context) override {
791    return run(Nodes);
792  }
793
794private:
795  const std::string Id;
796  const int ExpectedCount;
797  int Count;
798  const std::string ExpectedName;
799  std::string Name;
800};
801
802TEST(HasDescendant, MatchesDescendantTypes) {
803  EXPECT_TRUE(matches("void f() { int i = 3; }",
804                      decl(hasDescendant(loc(builtinType())))));
805  EXPECT_TRUE(matches("void f() { int i = 3; }",
806                      stmt(hasDescendant(builtinType()))));
807
808  EXPECT_TRUE(matches("void f() { int i = 3; }",
809                      stmt(hasDescendant(loc(builtinType())))));
810  EXPECT_TRUE(matches("void f() { int i = 3; }",
811                      stmt(hasDescendant(qualType(builtinType())))));
812
813  EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
814                         stmt(hasDescendant(isInteger()))));
815
816  EXPECT_TRUE(matchAndVerifyResultTrue(
817      "void f() { int a; float c; int d; int e; }",
818      functionDecl(forEachDescendant(
819          varDecl(hasDescendant(isInteger())).bind("x"))),
820      new VerifyIdIsBoundTo<Decl>("x", 3)));
821}
822
823TEST(HasDescendant, MatchesDescendantsOfTypes) {
824  EXPECT_TRUE(matches("void f() { int*** i; }",
825                      qualType(hasDescendant(builtinType()))));
826  EXPECT_TRUE(matches("void f() { int*** i; }",
827                      qualType(hasDescendant(
828                          pointerType(pointee(builtinType()))))));
829  EXPECT_TRUE(matches("void f() { int*** i; }",
830                      typeLoc(hasDescendant(loc(builtinType())))));
831
832  EXPECT_TRUE(matchAndVerifyResultTrue(
833      "void f() { int*** i; }",
834      qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
835      new VerifyIdIsBoundTo<Type>("x", 2)));
836}
837
838TEST(Has, MatchesChildrenOfTypes) {
839  EXPECT_TRUE(matches("int i;",
840                      varDecl(hasName("i"), has(isInteger()))));
841  EXPECT_TRUE(notMatches("int** i;",
842                         varDecl(hasName("i"), has(isInteger()))));
843  EXPECT_TRUE(matchAndVerifyResultTrue(
844      "int (*f)(float, int);",
845      qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
846      new VerifyIdIsBoundTo<QualType>("x", 2)));
847}
848
849TEST(Has, MatchesChildTypes) {
850  EXPECT_TRUE(matches(
851      "int* i;",
852      varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
853  EXPECT_TRUE(notMatches(
854      "int* i;",
855      varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
856}
857
858TEST(ValueDecl, Matches) {
859  EXPECT_TRUE(matches("enum EnumType { EnumValue };",
860                      valueDecl(hasType(asString("enum EnumType")))));
861  EXPECT_TRUE(matches("void FunctionDecl();",
862                      valueDecl(hasType(asString("void (void)")))));
863}
864
865TEST(Enum, DoesNotMatchClasses) {
866  EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
867}
868
869TEST(Enum, MatchesEnums) {
870  EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
871}
872
873TEST(EnumConstant, Matches) {
874  DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
875  EXPECT_TRUE(matches("enum X{ A };", Matcher));
876  EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
877  EXPECT_TRUE(notMatches("enum X {};", Matcher));
878}
879
880TEST(StatementMatcher, Has) {
881  StatementMatcher HasVariableI =
882      expr(hasType(pointsTo(recordDecl(hasName("X")))),
883           has(declRefExpr(to(varDecl(hasName("i"))))));
884
885  EXPECT_TRUE(matches(
886      "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
887  EXPECT_TRUE(notMatches(
888      "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
889}
890
891TEST(StatementMatcher, HasDescendant) {
892  StatementMatcher HasDescendantVariableI =
893      expr(hasType(pointsTo(recordDecl(hasName("X")))),
894           hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
895
896  EXPECT_TRUE(matches(
897      "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
898      HasDescendantVariableI));
899  EXPECT_TRUE(notMatches(
900      "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
901      HasDescendantVariableI));
902}
903
904TEST(TypeMatcher, MatchesClassType) {
905  TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
906
907  EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
908  EXPECT_TRUE(notMatches("class A {};", TypeA));
909
910  TypeMatcher TypeDerivedFromA =
911      hasDeclaration(cxxRecordDecl(isDerivedFrom("A")));
912
913  EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
914              TypeDerivedFromA));
915  EXPECT_TRUE(notMatches("class A {};", TypeA));
916
917  TypeMatcher TypeAHasClassB = hasDeclaration(
918      recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
919
920  EXPECT_TRUE(
921      matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
922
923  EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }",
924                       varDecl(hasType(namedDecl(hasName("S"))))));
925}
926
927TEST(TypeMatcher, MatchesDeclTypes) {
928  // TypedefType -> TypedefNameDecl
929  EXPECT_TRUE(matches("typedef int I; void f(I i);",
930                      parmVarDecl(hasType(namedDecl(hasName("I"))))));
931  // ObjCObjectPointerType
932  EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);",
933                          parmVarDecl(hasType(objcObjectPointerType()))));
934  // ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl
935  EXPECT_TRUE(matchesObjC(
936      "@interface Foo @end void f(Foo *f);",
937      parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo")))))));
938  // TemplateTypeParmType
939  EXPECT_TRUE(matches("template <typename T> void f(T t);",
940                      parmVarDecl(hasType(templateTypeParmType()))));
941  // TemplateTypeParmType -> TemplateTypeParmDecl
942  EXPECT_TRUE(matches("template <typename T> void f(T t);",
943                      parmVarDecl(hasType(namedDecl(hasName("T"))))));
944  // InjectedClassNameType
945  EXPECT_TRUE(matches("template <typename T> struct S {"
946                      "  void f(S s);"
947                      "};",
948                      parmVarDecl(hasType(injectedClassNameType()))));
949  EXPECT_TRUE(notMatches("template <typename T> struct S {"
950                         "  void g(S<T> s);"
951                         "};",
952                         parmVarDecl(hasType(injectedClassNameType()))));
953  // InjectedClassNameType -> CXXRecordDecl
954  EXPECT_TRUE(matches("template <typename T> struct S {"
955                      "  void f(S s);"
956                      "};",
957                      parmVarDecl(hasType(namedDecl(hasName("S"))))));
958
959  static const char Using[] = "template <typename T>"
960                              "struct Base {"
961                              "  typedef T Foo;"
962                              "};"
963                              ""
964                              "template <typename T>"
965                              "struct S : private Base<T> {"
966                              "  using typename Base<T>::Foo;"
967                              "  void f(Foo);"
968                              "};";
969  // UnresolvedUsingTypenameDecl
970  EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo"))));
971  // UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl
972  EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo"))))));
973}
974
975TEST(Matcher, BindMatchedNodes) {
976  DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
977
978  EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
979      ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
980
981  EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
982      ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
983
984  TypeMatcher TypeAHasClassB = hasDeclaration(
985      recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
986
987  EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
988      TypeAHasClassB,
989      new VerifyIdIsBoundTo<Decl>("b")));
990
991  StatementMatcher MethodX =
992      callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
993
994  EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
995      MethodX,
996      new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
997}
998
999TEST(Matcher, BindTheSameNameInAlternatives) {
1000  StatementMatcher matcher = anyOf(
1001      binaryOperator(hasOperatorName("+"),
1002                     hasLHS(expr().bind("x")),
1003                     hasRHS(integerLiteral(equals(0)))),
1004      binaryOperator(hasOperatorName("+"),
1005                     hasLHS(integerLiteral(equals(0))),
1006                     hasRHS(expr().bind("x"))));
1007
1008  EXPECT_TRUE(matchAndVerifyResultTrue(
1009      // The first branch of the matcher binds x to 0 but then fails.
1010      // The second branch binds x to f() and succeeds.
1011      "int f() { return 0 + f(); }",
1012      matcher,
1013      new VerifyIdIsBoundTo<CallExpr>("x")));
1014}
1015
1016TEST(Matcher, BindsIDForMemoizedResults) {
1017  // Using the same matcher in two match expressions will make memoization
1018  // kick in.
1019  DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
1020  EXPECT_TRUE(matchAndVerifyResultTrue(
1021      "class A { class B { class X {}; }; };",
1022      DeclarationMatcher(anyOf(
1023          recordDecl(hasName("A"), hasDescendant(ClassX)),
1024          recordDecl(hasName("B"), hasDescendant(ClassX)))),
1025      new VerifyIdIsBoundTo<Decl>("x", 2)));
1026}
1027
1028TEST(HasDeclaration, HasDeclarationOfEnumType) {
1029  EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
1030                      expr(hasType(pointsTo(
1031                          qualType(hasDeclaration(enumDecl(hasName("X")))))))));
1032}
1033
1034TEST(HasDeclaration, HasGetDeclTraitTest) {
1035  EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
1036  EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
1037  EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
1038}
1039
1040TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
1041  EXPECT_TRUE(matches("typedef int X; X a;",
1042                      varDecl(hasName("a"),
1043                              hasType(typedefType(hasDeclaration(decl()))))));
1044
1045  // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
1046}
1047
1048TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
1049  EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
1050                      varDecl(hasType(templateSpecializationType(
1051                          hasDeclaration(namedDecl(hasName("A"))))))));
1052}
1053
1054TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
1055  TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
1056  EXPECT_TRUE(
1057      matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
1058  EXPECT_TRUE(
1059      notMatches("class X {}; void y(X *x) { x; }",
1060                 expr(hasType(ClassX))));
1061  EXPECT_TRUE(
1062      matches("class X {}; void y(X *x) { x; }",
1063              expr(hasType(pointsTo(ClassX)))));
1064}
1065
1066TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
1067  TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
1068  EXPECT_TRUE(
1069      matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
1070  EXPECT_TRUE(
1071      notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
1072  EXPECT_TRUE(
1073      matches("class X {}; void y() { X *x; }",
1074              varDecl(hasType(pointsTo(ClassX)))));
1075}
1076
1077TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
1078  DeclarationMatcher ClassX = recordDecl(hasName("X"));
1079  EXPECT_TRUE(
1080      matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
1081  EXPECT_TRUE(
1082      notMatches("class X {}; void y(X *x) { x; }",
1083                 expr(hasType(ClassX))));
1084}
1085
1086TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
1087  DeclarationMatcher ClassX = recordDecl(hasName("X"));
1088  EXPECT_TRUE(
1089      matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
1090  EXPECT_TRUE(
1091      notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
1092}
1093
1094TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1095  EXPECT_TRUE(matches("int x;",
1096                      varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1097
1098  // Make sure we don't crash on implicit constructors.
1099  EXPECT_TRUE(notMatches("class X {}; X x;",
1100                         declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1101}
1102
1103TEST(Matcher, Call) {
1104  // FIXME: Do we want to overload Call() to directly take
1105  // Matcher<Decl>, too?
1106  StatementMatcher MethodX =
1107      callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
1108
1109  EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1110  EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1111
1112  StatementMatcher MethodOnY =
1113      cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
1114
1115  EXPECT_TRUE(
1116      matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1117              MethodOnY));
1118  EXPECT_TRUE(
1119      matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1120              MethodOnY));
1121  EXPECT_TRUE(
1122      notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1123                 MethodOnY));
1124  EXPECT_TRUE(
1125      notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1126                 MethodOnY));
1127  EXPECT_TRUE(
1128      notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1129                 MethodOnY));
1130
1131  StatementMatcher MethodOnYPointer =
1132      cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
1133
1134  EXPECT_TRUE(
1135      matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1136              MethodOnYPointer));
1137  EXPECT_TRUE(
1138      matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1139              MethodOnYPointer));
1140  EXPECT_TRUE(
1141      matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1142              MethodOnYPointer));
1143  EXPECT_TRUE(
1144      notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1145                 MethodOnYPointer));
1146  EXPECT_TRUE(
1147      notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1148                 MethodOnYPointer));
1149}
1150
1151TEST(Matcher, Lambda) {
1152  EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
1153                      lambdaExpr()));
1154}
1155
1156TEST(Matcher, ForRange) {
1157  EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1158                      "void f() { for (auto &a : as); }",
1159                      cxxForRangeStmt()));
1160  EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1161                         cxxForRangeStmt()));
1162}
1163
1164TEST(Matcher, SubstNonTypeTemplateParm) {
1165  EXPECT_FALSE(matches("template<int N>\n"
1166                       "struct A {  static const int n = 0; };\n"
1167                       "struct B : public A<42> {};",
1168                       substNonTypeTemplateParmExpr()));
1169  EXPECT_TRUE(matches("template<int N>\n"
1170                      "struct A {  static const int n = N; };\n"
1171                      "struct B : public A<42> {};",
1172                      substNonTypeTemplateParmExpr()));
1173}
1174
1175TEST(Matcher, NonTypeTemplateParmDecl) {
1176  EXPECT_TRUE(matches("template <int N> void f();",
1177                      nonTypeTemplateParmDecl(hasName("N"))));
1178  EXPECT_TRUE(
1179      notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
1180}
1181
1182TEST(Matcher, templateTypeParmDecl) {
1183  EXPECT_TRUE(matches("template <typename T> void f();",
1184                      templateTypeParmDecl(hasName("T"))));
1185  EXPECT_TRUE(
1186      notMatches("template <int N> void f();", templateTypeParmDecl()));
1187}
1188
1189TEST(Matcher, UserDefinedLiteral) {
1190  EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1191                      "  return i + 1;"
1192                      "}"
1193                      "char c = 'a'_inc;",
1194                      userDefinedLiteral()));
1195}
1196
1197TEST(Matcher, FlowControl) {
1198  EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1199  EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1200                      continueStmt()));
1201  EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1202  EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1203  EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1204}
1205
1206TEST(HasType, MatchesAsString) {
1207  EXPECT_TRUE(
1208      matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
1209              cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
1210  EXPECT_TRUE(
1211      matches("class X { void x(int x) {} };",
1212              cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
1213  EXPECT_TRUE(matches("namespace ns { struct A {}; }  struct B { ns::A a; };",
1214      fieldDecl(hasType(asString("ns::A")))));
1215  EXPECT_TRUE(matches("namespace { struct A {}; }  struct B { A a; };",
1216      fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
1217}
1218
1219TEST(Matcher, OverloadedOperatorCall) {
1220  StatementMatcher OpCall = cxxOperatorCallExpr();
1221  // Unary operator
1222  EXPECT_TRUE(matches("class Y { }; "
1223              "bool operator!(Y x) { return false; }; "
1224              "Y y; bool c = !y;", OpCall));
1225  // No match -- special operators like "new", "delete"
1226  // FIXME: operator new takes size_t, for which we need stddef.h, for which
1227  // we need to figure out include paths in the test.
1228  // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1229  //             "class Y { }; "
1230  //             "void *operator new(size_t size) { return 0; } "
1231  //             "Y *y = new Y;", OpCall));
1232  EXPECT_TRUE(notMatches("class Y { }; "
1233              "void operator delete(void *p) { } "
1234              "void a() {Y *y = new Y; delete y;}", OpCall));
1235  // Binary operator
1236  EXPECT_TRUE(matches("class Y { }; "
1237              "bool operator&&(Y x, Y y) { return true; }; "
1238              "Y a; Y b; bool c = a && b;",
1239              OpCall));
1240  // No match -- normal operator, not an overloaded one.
1241  EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1242  EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1243}
1244
1245TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1246  StatementMatcher OpCallAndAnd =
1247      cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
1248  EXPECT_TRUE(matches("class Y { }; "
1249              "bool operator&&(Y x, Y y) { return true; }; "
1250              "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1251  StatementMatcher OpCallLessLess =
1252      cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
1253  EXPECT_TRUE(notMatches("class Y { }; "
1254              "bool operator&&(Y x, Y y) { return true; }; "
1255              "Y a; Y b; bool c = a && b;",
1256              OpCallLessLess));
1257  StatementMatcher OpStarCall =
1258      cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
1259  EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1260              OpStarCall));
1261  DeclarationMatcher ClassWithOpStar =
1262    cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
1263  EXPECT_TRUE(matches("class Y { int operator*(); };",
1264                      ClassWithOpStar));
1265  EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1266              ClassWithOpStar)) ;
1267  DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1268  EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1269  EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
1270}
1271
1272TEST(Matcher, NestedOverloadedOperatorCalls) {
1273  EXPECT_TRUE(matchAndVerifyResultTrue(
1274      "class Y { }; "
1275      "Y& operator&&(Y& x, Y& y) { return x; }; "
1276      "Y a; Y b; Y c; Y d = a && b && c;",
1277      cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1278      new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1279  EXPECT_TRUE(matches("class Y { }; "
1280                      "Y& operator&&(Y& x, Y& y) { return x; }; "
1281                      "Y a; Y b; Y c; Y d = a && b && c;",
1282                      cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
1283  EXPECT_TRUE(
1284      matches("class Y { }; "
1285              "Y& operator&&(Y& x, Y& y) { return x; }; "
1286              "Y a; Y b; Y c; Y d = a && b && c;",
1287              cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
1288}
1289
1290TEST(Matcher, ThisPointerType) {
1291  StatementMatcher MethodOnY =
1292    cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
1293
1294  EXPECT_TRUE(
1295      matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1296              MethodOnY));
1297  EXPECT_TRUE(
1298      matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1299              MethodOnY));
1300  EXPECT_TRUE(
1301      matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1302              MethodOnY));
1303  EXPECT_TRUE(
1304      matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1305              MethodOnY));
1306  EXPECT_TRUE(
1307      matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1308              MethodOnY));
1309
1310  EXPECT_TRUE(matches(
1311      "class Y {"
1312      "  public: virtual void x();"
1313      "};"
1314      "class X : public Y {"
1315      "  public: virtual void x();"
1316      "};"
1317      "void z() { X *x; x->Y::x(); }", MethodOnY));
1318}
1319
1320TEST(Matcher, VariableUsage) {
1321  StatementMatcher Reference =
1322      declRefExpr(to(
1323          varDecl(hasInitializer(
1324              cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
1325
1326  EXPECT_TRUE(matches(
1327      "class Y {"
1328      " public:"
1329      "  bool x() const;"
1330      "};"
1331      "void z(const Y &y) {"
1332      "  bool b = y.x();"
1333      "  if (b) {}"
1334      "}", Reference));
1335
1336  EXPECT_TRUE(notMatches(
1337      "class Y {"
1338      " public:"
1339      "  bool x() const;"
1340      "};"
1341      "void z(const Y &y) {"
1342      "  bool b = y.x();"
1343      "}", Reference));
1344}
1345
1346TEST(Matcher, VarDecl_Storage) {
1347  auto M = varDecl(hasName("X"), hasLocalStorage());
1348  EXPECT_TRUE(matches("void f() { int X; }", M));
1349  EXPECT_TRUE(notMatches("int X;", M));
1350  EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1351
1352  M = varDecl(hasName("X"), hasGlobalStorage());
1353  EXPECT_TRUE(notMatches("void f() { int X; }", M));
1354  EXPECT_TRUE(matches("int X;", M));
1355  EXPECT_TRUE(matches("void f() { static int X; }", M));
1356}
1357
1358TEST(Matcher, VarDecl_StorageDuration) {
1359  std::string T =
1360      "void f() { int x; static int y; } int a;";
1361
1362  EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
1363  EXPECT_TRUE(
1364      notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
1365  EXPECT_TRUE(
1366      notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
1367
1368  EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
1369  EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
1370  EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
1371
1372  // FIXME: It is really hard to test with thread_local itself because not all
1373  // targets support TLS, which causes this to be an error depending on what
1374  // platform the test is being run on. We do not have access to the TargetInfo
1375  // object to be able to test whether the platform supports TLS or not.
1376  EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
1377  EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
1378  EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
1379}
1380
1381TEST(Matcher, FindsVarDeclInFunctionParameter) {
1382  EXPECT_TRUE(matches(
1383      "void f(int i) {}",
1384      varDecl(hasName("i"))));
1385}
1386
1387TEST(Matcher, CalledVariable) {
1388  StatementMatcher CallOnVariableY =
1389      cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
1390
1391  EXPECT_TRUE(matches(
1392      "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1393  EXPECT_TRUE(matches(
1394      "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1395  EXPECT_TRUE(matches(
1396      "class Y { public: void x(); };"
1397      "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1398  EXPECT_TRUE(matches(
1399      "class Y { public: void x(); };"
1400      "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1401  EXPECT_TRUE(notMatches(
1402      "class Y { public: void x(); };"
1403      "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1404      CallOnVariableY));
1405}
1406
1407TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1408  EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1409                      unaryExprOrTypeTraitExpr()));
1410  EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1411                         alignOfExpr(anything())));
1412  // FIXME: Uncomment once alignof is enabled.
1413  // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1414  //                     unaryExprOrTypeTraitExpr()));
1415  // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1416  //                        sizeOfExpr()));
1417}
1418
1419TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1420  EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1421      hasArgumentOfType(asString("int")))));
1422  EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1423      hasArgumentOfType(asString("float")))));
1424  EXPECT_TRUE(matches(
1425      "struct A {}; void x() { A a; int b = sizeof(a); }",
1426      sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
1427  EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1428      hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
1429}
1430
1431TEST(MemberExpression, DoesNotMatchClasses) {
1432  EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
1433}
1434
1435TEST(MemberExpression, MatchesMemberFunctionCall) {
1436  EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
1437}
1438
1439TEST(MemberExpression, MatchesVariable) {
1440  EXPECT_TRUE(
1441      matches("class Y { void x() { this->y; } int y; };", memberExpr()));
1442  EXPECT_TRUE(
1443      matches("class Y { void x() { y; } int y; };", memberExpr()));
1444  EXPECT_TRUE(
1445      matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
1446}
1447
1448TEST(MemberExpression, MatchesStaticVariable) {
1449  EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
1450              memberExpr()));
1451  EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
1452              memberExpr()));
1453  EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
1454              memberExpr()));
1455}
1456
1457TEST(IsInteger, MatchesIntegers) {
1458  EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1459  EXPECT_TRUE(matches(
1460      "long long i = 0; void f(long long) { }; void g() {f(i);}",
1461      callExpr(hasArgument(0, declRefExpr(
1462                                  to(varDecl(hasType(isInteger()))))))));
1463}
1464
1465TEST(IsInteger, ReportsNoFalsePositives) {
1466  EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
1467  EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
1468                      callExpr(hasArgument(0, declRefExpr(
1469                          to(varDecl(hasType(isInteger()))))))));
1470}
1471
1472TEST(IsAnyCharacter, MatchesCharacters) {
1473  EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
1474}
1475
1476TEST(IsAnyCharacter, ReportsNoFalsePositives) {
1477  EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
1478}
1479
1480TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1481  EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
1482              memberExpr(isArrow())));
1483  EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
1484              memberExpr(isArrow())));
1485  EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
1486              memberExpr(isArrow())));
1487}
1488
1489TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1490  EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
1491              memberExpr(isArrow())));
1492  EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
1493              memberExpr(isArrow())));
1494  EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
1495              memberExpr(isArrow())));
1496}
1497
1498TEST(IsArrow, MatchesMemberCallsViaArrow) {
1499  EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
1500              memberExpr(isArrow())));
1501  EXPECT_TRUE(matches("class Y { void x() { x(); } };",
1502              memberExpr(isArrow())));
1503  EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
1504              memberExpr(isArrow())));
1505}
1506
1507TEST(Callee, MatchesDeclarations) {
1508  StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
1509
1510  EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1511  EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1512
1513  CallMethodX = callExpr(callee(cxxConversionDecl()));
1514  EXPECT_TRUE(
1515      matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1516  EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1517                         CallMethodX));
1518}
1519
1520TEST(ConversionDeclaration, IsExplicit) {
1521  EXPECT_TRUE(matches("struct S { explicit operator int(); };",
1522                      cxxConversionDecl(isExplicit())));
1523  EXPECT_TRUE(notMatches("struct S { operator int(); };",
1524                         cxxConversionDecl(isExplicit())));
1525}
1526
1527TEST(Callee, MatchesMemberExpressions) {
1528  EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
1529              callExpr(callee(memberExpr()))));
1530  EXPECT_TRUE(
1531      notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
1532}
1533
1534TEST(Function, MatchesFunctionDeclarations) {
1535  StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
1536
1537  EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1538  EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1539
1540  if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1541      llvm::Triple::Win32) {
1542    // FIXME: Make this work for MSVC.
1543    // Dependent contexts, but a non-dependent call.
1544    EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1545                        CallFunctionF));
1546    EXPECT_TRUE(
1547        matches("void f(); template <int N> struct S { void g() { f(); } };",
1548                CallFunctionF));
1549  }
1550
1551  // Depedent calls don't match.
1552  EXPECT_TRUE(
1553      notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1554                 CallFunctionF));
1555  EXPECT_TRUE(
1556      notMatches("void f(int);"
1557                 "template <typename T> struct S { void g(T t) { f(t); } };",
1558                 CallFunctionF));
1559
1560  EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
1561  EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
1562  EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
1563                         functionDecl(isVariadic())));
1564  EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
1565  EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
1566}
1567
1568TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1569  EXPECT_TRUE(
1570      matches("template <typename T> void f(T t) {}",
1571      functionTemplateDecl(hasName("f"))));
1572}
1573
1574TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1575  EXPECT_TRUE(
1576      notMatches("void f(double d); void f(int t) {}",
1577      functionTemplateDecl(hasName("f"))));
1578}
1579
1580TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1581  EXPECT_TRUE(
1582      notMatches("void g(); template <typename T> void f(T t) {}"
1583                 "template <> void f(int t) { g(); }",
1584      functionTemplateDecl(hasName("f"),
1585                           hasDescendant(declRefExpr(to(
1586                               functionDecl(hasName("g"))))))));
1587}
1588
1589TEST(Matcher, Argument) {
1590  StatementMatcher CallArgumentY = callExpr(
1591      hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
1592
1593  EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1594  EXPECT_TRUE(
1595      matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1596  EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1597
1598  StatementMatcher WrongIndex = callExpr(
1599      hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
1600  EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1601}
1602
1603TEST(Matcher, AnyArgument) {
1604  StatementMatcher CallArgumentY = callExpr(
1605      hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
1606  EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1607  EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1608  EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1609}
1610
1611TEST(Matcher, ArgumentCount) {
1612  StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
1613
1614  EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1615  EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1616  EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1617}
1618
1619TEST(Matcher, ParameterCount) {
1620  DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1621  EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1622  EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1623  EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1624  EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1625}
1626
1627TEST(Matcher, References) {
1628  DeclarationMatcher ReferenceClassX = varDecl(
1629      hasType(references(recordDecl(hasName("X")))));
1630  EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1631                      ReferenceClassX));
1632  EXPECT_TRUE(
1633      matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
1634  // The match here is on the implicit copy constructor code for
1635  // class X, not on code 'X x = y'.
1636  EXPECT_TRUE(
1637      matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1638  EXPECT_TRUE(
1639      notMatches("class X {}; extern X x;", ReferenceClassX));
1640  EXPECT_TRUE(
1641      notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1642}
1643
1644TEST(QualType, hasCanonicalType) {
1645  EXPECT_TRUE(notMatches("typedef int &int_ref;"
1646                         "int a;"
1647                         "int_ref b = a;",
1648                         varDecl(hasType(qualType(referenceType())))));
1649  EXPECT_TRUE(
1650      matches("typedef int &int_ref;"
1651              "int a;"
1652              "int_ref b = a;",
1653              varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1654}
1655
1656TEST(QualType, hasLocalQualifiers) {
1657  EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1658                         varDecl(hasType(hasLocalQualifiers()))));
1659  EXPECT_TRUE(matches("int *const j = nullptr;",
1660                      varDecl(hasType(hasLocalQualifiers()))));
1661  EXPECT_TRUE(matches("int *volatile k;",
1662                      varDecl(hasType(hasLocalQualifiers()))));
1663  EXPECT_TRUE(notMatches("int m;",
1664                         varDecl(hasType(hasLocalQualifiers()))));
1665}
1666
1667TEST(HasParameter, CallsInnerMatcher) {
1668  EXPECT_TRUE(matches("class X { void x(int) {} };",
1669                      cxxMethodDecl(hasParameter(0, varDecl()))));
1670  EXPECT_TRUE(notMatches("class X { void x(int) {} };",
1671                         cxxMethodDecl(hasParameter(0, hasName("x")))));
1672}
1673
1674TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1675  EXPECT_TRUE(notMatches("class X { void x(int) {} };",
1676                         cxxMethodDecl(hasParameter(42, varDecl()))));
1677}
1678
1679TEST(HasType, MatchesParameterVariableTypesStrictly) {
1680  EXPECT_TRUE(matches(
1681      "class X { void x(X x) {} };",
1682      cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
1683  EXPECT_TRUE(notMatches(
1684      "class X { void x(const X &x) {} };",
1685      cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
1686  EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
1687                      cxxMethodDecl(hasParameter(
1688                          0, hasType(pointsTo(recordDecl(hasName("X"))))))));
1689  EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
1690                      cxxMethodDecl(hasParameter(
1691                          0, hasType(references(recordDecl(hasName("X"))))))));
1692}
1693
1694TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1695  EXPECT_TRUE(matches(
1696      "class Y {}; class X { void x(X x, Y y) {} };",
1697      cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
1698  EXPECT_TRUE(matches(
1699      "class Y {}; class X { void x(Y y, X x) {} };",
1700      cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
1701}
1702
1703TEST(Returns, MatchesReturnTypes) {
1704  EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
1705                      functionDecl(returns(asString("int")))));
1706  EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
1707                         functionDecl(returns(asString("float")))));
1708  EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
1709                      functionDecl(returns(hasDeclaration(
1710                          recordDecl(hasName("Y")))))));
1711}
1712
1713TEST(IsExternC, MatchesExternCFunctionDeclarations) {
1714  EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1715  EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1716              functionDecl(isExternC())));
1717  EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
1718}
1719
1720TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1721  EXPECT_TRUE(
1722      notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1723  EXPECT_TRUE(matches("void Func() = delete;",
1724                      functionDecl(hasName("Func"), isDeleted())));
1725}
1726
1727TEST(IsNoThrow, MatchesNoThrowFunctionDeclarations) {
1728  EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
1729  EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
1730  EXPECT_TRUE(
1731      notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
1732  EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
1733  EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
1734}
1735
1736TEST(isConstexpr, MatchesConstexprDeclarations) {
1737  EXPECT_TRUE(matches("constexpr int foo = 42;",
1738                      varDecl(hasName("foo"), isConstexpr())));
1739  EXPECT_TRUE(matches("constexpr int bar();",
1740                      functionDecl(hasName("bar"), isConstexpr())));
1741}
1742
1743TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1744  EXPECT_TRUE(notMatches(
1745      "class Y {}; class X { void x(int) {} };",
1746      cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
1747}
1748
1749TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1750  EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
1751                         cxxMethodDecl(hasAnyParameter(
1752                             hasType(pointsTo(recordDecl(hasName("X"))))))));
1753}
1754
1755TEST(HasName, MatchesParameterVariableDeclarations) {
1756  EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
1757                      cxxMethodDecl(hasAnyParameter(hasName("x")))));
1758  EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
1759                         cxxMethodDecl(hasAnyParameter(hasName("x")))));
1760}
1761
1762TEST(Matcher, MatchesClassTemplateSpecialization) {
1763  EXPECT_TRUE(matches("template<typename T> struct A {};"
1764                      "template<> struct A<int> {};",
1765                      classTemplateSpecializationDecl()));
1766  EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
1767                      classTemplateSpecializationDecl()));
1768  EXPECT_TRUE(notMatches("template<typename T> struct A {};",
1769                         classTemplateSpecializationDecl()));
1770}
1771
1772TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1773  EXPECT_TRUE(matches("int x;", declaratorDecl()));
1774  EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1775}
1776
1777TEST(ParmVarDecl, MatchesParmVars) {
1778  EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1779  EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1780}
1781
1782TEST(Matcher, MatchesTypeTemplateArgument) {
1783  EXPECT_TRUE(matches(
1784      "template<typename T> struct B {};"
1785      "B<int> b;",
1786      classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
1787          asString("int"))))));
1788}
1789
1790TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1791  EXPECT_TRUE(matches(
1792      "struct B { int next; };"
1793      "template<int(B::*next_ptr)> struct A {};"
1794      "A<&B::next> a;",
1795      classTemplateSpecializationDecl(hasAnyTemplateArgument(
1796          refersToDeclaration(fieldDecl(hasName("next")))))));
1797
1798  EXPECT_TRUE(notMatches(
1799      "template <typename T> struct A {};"
1800      "A<int> a;",
1801      classTemplateSpecializationDecl(hasAnyTemplateArgument(
1802          refersToDeclaration(decl())))));
1803
1804  EXPECT_TRUE(matches(
1805      "struct B { int next; };"
1806      "template<int(B::*next_ptr)> struct A {};"
1807      "A<&B::next> a;",
1808      templateSpecializationType(hasAnyTemplateArgument(isExpr(
1809          hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1810
1811  EXPECT_TRUE(notMatches(
1812      "template <typename T> struct A {};"
1813      "A<int> a;",
1814      templateSpecializationType(hasAnyTemplateArgument(
1815          refersToDeclaration(decl())))));
1816}
1817
1818TEST(Matcher, MatchesSpecificArgument) {
1819  EXPECT_TRUE(matches(
1820      "template<typename T, typename U> class A {};"
1821      "A<bool, int> a;",
1822      classTemplateSpecializationDecl(hasTemplateArgument(
1823          1, refersToType(asString("int"))))));
1824  EXPECT_TRUE(notMatches(
1825      "template<typename T, typename U> class A {};"
1826      "A<int, bool> a;",
1827      classTemplateSpecializationDecl(hasTemplateArgument(
1828          1, refersToType(asString("int"))))));
1829
1830  EXPECT_TRUE(matches(
1831      "template<typename T, typename U> class A {};"
1832      "A<bool, int> a;",
1833      templateSpecializationType(hasTemplateArgument(
1834          1, refersToType(asString("int"))))));
1835  EXPECT_TRUE(notMatches(
1836      "template<typename T, typename U> class A {};"
1837      "A<int, bool> a;",
1838      templateSpecializationType(hasTemplateArgument(
1839          1, refersToType(asString("int"))))));
1840}
1841
1842TEST(TemplateArgument, Matches) {
1843  EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1844                      classTemplateSpecializationDecl(
1845                          hasAnyTemplateArgument(templateArgument()))));
1846  EXPECT_TRUE(matches(
1847      "template<typename T> struct C {}; C<int> c;",
1848      templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1849}
1850
1851TEST(TemplateArgumentCountIs, Matches) {
1852  EXPECT_TRUE(
1853      matches("template<typename T> struct C {}; C<int> c;",
1854              classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1855  EXPECT_TRUE(
1856      notMatches("template<typename T> struct C {}; C<int> c;",
1857                 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1858
1859  EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1860                      templateSpecializationType(templateArgumentCountIs(1))));
1861  EXPECT_TRUE(
1862      notMatches("template<typename T> struct C {}; C<int> c;",
1863                 templateSpecializationType(templateArgumentCountIs(2))));
1864}
1865
1866TEST(IsIntegral, Matches) {
1867  EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1868                      classTemplateSpecializationDecl(
1869                          hasAnyTemplateArgument(isIntegral()))));
1870  EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1871                         classTemplateSpecializationDecl(hasAnyTemplateArgument(
1872                             templateArgument(isIntegral())))));
1873}
1874
1875TEST(RefersToIntegralType, Matches) {
1876  EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1877                      classTemplateSpecializationDecl(
1878                          hasAnyTemplateArgument(refersToIntegralType(
1879                              asString("int"))))));
1880  EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1881                         classTemplateSpecializationDecl(hasAnyTemplateArgument(
1882                             refersToIntegralType(asString("int"))))));
1883}
1884
1885TEST(EqualsIntegralValue, Matches) {
1886  EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1887                      classTemplateSpecializationDecl(
1888                          hasAnyTemplateArgument(equalsIntegralValue("42")))));
1889  EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1890                      classTemplateSpecializationDecl(
1891                          hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1892  EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1893                      classTemplateSpecializationDecl(
1894                          hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1895  EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1896                         classTemplateSpecializationDecl(hasAnyTemplateArgument(
1897                             equalsIntegralValue("0042")))));
1898}
1899
1900TEST(Matcher, MatchesAccessSpecDecls) {
1901  EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1902  EXPECT_TRUE(
1903      matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1904  EXPECT_TRUE(
1905      notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1906  EXPECT_TRUE(
1907      notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1908
1909  EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1910}
1911
1912TEST(Matcher, MatchesFinal) {
1913  EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
1914  EXPECT_TRUE(matches("class X { virtual void f() final; };",
1915                      cxxMethodDecl(isFinal())));
1916  EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
1917  EXPECT_TRUE(
1918      notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
1919}
1920
1921TEST(Matcher, MatchesVirtualMethod) {
1922  EXPECT_TRUE(matches("class X { virtual int f(); };",
1923                      cxxMethodDecl(isVirtual(), hasName("::X::f"))));
1924  EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
1925}
1926
1927TEST(Matcher, MatchesPureMethod) {
1928  EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1929                      cxxMethodDecl(isPure(), hasName("::X::f"))));
1930  EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
1931}
1932
1933TEST(Matcher, MatchesCopyAssignmentOperator) {
1934  EXPECT_TRUE(matches("class X { X &operator=(X); };",
1935                      cxxMethodDecl(isCopyAssignmentOperator())));
1936  EXPECT_TRUE(matches("class X { X &operator=(X &); };",
1937                      cxxMethodDecl(isCopyAssignmentOperator())));
1938  EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
1939                      cxxMethodDecl(isCopyAssignmentOperator())));
1940  EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
1941                      cxxMethodDecl(isCopyAssignmentOperator())));
1942  EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
1943                      cxxMethodDecl(isCopyAssignmentOperator())));
1944  EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
1945                      cxxMethodDecl(isCopyAssignmentOperator())));
1946}
1947
1948TEST(Matcher, MatchesConstMethod) {
1949  EXPECT_TRUE(
1950      matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
1951  EXPECT_TRUE(
1952      notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
1953}
1954
1955TEST(Matcher, MatchesOverridingMethod) {
1956  EXPECT_TRUE(matches("class X { virtual int f(); }; "
1957                      "class Y : public X { int f(); };",
1958                      cxxMethodDecl(isOverride(), hasName("::Y::f"))));
1959  EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1960                         "class Y : public X { int f(); };",
1961                         cxxMethodDecl(isOverride(), hasName("::X::f"))));
1962  EXPECT_TRUE(notMatches("class X { int f(); }; "
1963                         "class Y : public X { int f(); };",
1964                         cxxMethodDecl(isOverride())));
1965  EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1966                         cxxMethodDecl(isOverride())));
1967  EXPECT_TRUE(
1968      matches("template <typename Base> struct Y : Base { void f() override;};",
1969              cxxMethodDecl(isOverride(), hasName("::Y::f"))));
1970}
1971
1972TEST(Matcher, ConstructorCall) {
1973  StatementMatcher Constructor = cxxConstructExpr();
1974
1975  EXPECT_TRUE(
1976      matches("class X { public: X(); }; void x() { X x; }", Constructor));
1977  EXPECT_TRUE(
1978      matches("class X { public: X(); }; void x() { X x = X(); }",
1979              Constructor));
1980  EXPECT_TRUE(
1981      matches("class X { public: X(int); }; void x() { X x = 0; }",
1982              Constructor));
1983  EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1984}
1985
1986TEST(Matcher, ConstructorArgument) {
1987  StatementMatcher Constructor = cxxConstructExpr(
1988      hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
1989
1990  EXPECT_TRUE(
1991      matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1992              Constructor));
1993  EXPECT_TRUE(
1994      matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1995              Constructor));
1996  EXPECT_TRUE(
1997      matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1998              Constructor));
1999  EXPECT_TRUE(
2000      notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
2001                 Constructor));
2002
2003  StatementMatcher WrongIndex = cxxConstructExpr(
2004      hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
2005  EXPECT_TRUE(
2006      notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
2007                 WrongIndex));
2008}
2009
2010TEST(Matcher, ConstructorArgumentCount) {
2011  StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
2012
2013  EXPECT_TRUE(
2014      matches("class X { public: X(int); }; void x() { X x(0); }",
2015              Constructor1Arg));
2016  EXPECT_TRUE(
2017      matches("class X { public: X(int); }; void x() { X x = X(0); }",
2018              Constructor1Arg));
2019  EXPECT_TRUE(
2020      matches("class X { public: X(int); }; void x() { X x = 0; }",
2021              Constructor1Arg));
2022  EXPECT_TRUE(
2023      notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
2024                 Constructor1Arg));
2025}
2026
2027TEST(Matcher, ConstructorListInitialization) {
2028  StatementMatcher ConstructorListInit =
2029      cxxConstructExpr(isListInitialization());
2030
2031  EXPECT_TRUE(
2032      matches("class X { public: X(int); }; void x() { X x{0}; }",
2033              ConstructorListInit));
2034  EXPECT_FALSE(
2035      matches("class X { public: X(int); }; void x() { X x(0); }",
2036              ConstructorListInit));
2037}
2038
2039TEST(Matcher,ThisExpr) {
2040  EXPECT_TRUE(
2041      matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
2042  EXPECT_TRUE(
2043      notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
2044}
2045
2046TEST(Matcher, BindTemporaryExpression) {
2047  StatementMatcher TempExpression = cxxBindTemporaryExpr();
2048
2049  std::string ClassString = "class string { public: string(); ~string(); }; ";
2050
2051  EXPECT_TRUE(
2052      matches(ClassString +
2053              "string GetStringByValue();"
2054              "void FunctionTakesString(string s);"
2055              "void run() { FunctionTakesString(GetStringByValue()); }",
2056              TempExpression));
2057
2058  EXPECT_TRUE(
2059      notMatches(ClassString +
2060                 "string* GetStringPointer(); "
2061                 "void FunctionTakesStringPtr(string* s);"
2062                 "void run() {"
2063                 "  string* s = GetStringPointer();"
2064                 "  FunctionTakesStringPtr(GetStringPointer());"
2065                 "  FunctionTakesStringPtr(s);"
2066                 "}",
2067                 TempExpression));
2068
2069  EXPECT_TRUE(
2070      notMatches("class no_dtor {};"
2071                 "no_dtor GetObjByValue();"
2072                 "void ConsumeObj(no_dtor param);"
2073                 "void run() { ConsumeObj(GetObjByValue()); }",
2074                 TempExpression));
2075}
2076
2077TEST(MaterializeTemporaryExpr, MatchesTemporary) {
2078  std::string ClassString =
2079      "class string { public: string(); int length(); }; ";
2080
2081  EXPECT_TRUE(
2082      matches(ClassString +
2083              "string GetStringByValue();"
2084              "void FunctionTakesString(string s);"
2085              "void run() { FunctionTakesString(GetStringByValue()); }",
2086              materializeTemporaryExpr()));
2087
2088  EXPECT_TRUE(
2089      notMatches(ClassString +
2090                 "string* GetStringPointer(); "
2091                 "void FunctionTakesStringPtr(string* s);"
2092                 "void run() {"
2093                 "  string* s = GetStringPointer();"
2094                 "  FunctionTakesStringPtr(GetStringPointer());"
2095                 "  FunctionTakesStringPtr(s);"
2096                 "}",
2097                 materializeTemporaryExpr()));
2098
2099  EXPECT_TRUE(
2100      notMatches(ClassString +
2101                 "string GetStringByValue();"
2102                 "void run() { int k = GetStringByValue().length(); }",
2103                 materializeTemporaryExpr()));
2104
2105  EXPECT_TRUE(
2106      notMatches(ClassString +
2107                 "string GetStringByValue();"
2108                 "void run() { GetStringByValue(); }",
2109                 materializeTemporaryExpr()));
2110}
2111
2112TEST(ConstructorDeclaration, SimpleCase) {
2113  EXPECT_TRUE(matches("class Foo { Foo(int i); };",
2114                      cxxConstructorDecl(ofClass(hasName("Foo")))));
2115  EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
2116                         cxxConstructorDecl(ofClass(hasName("Bar")))));
2117}
2118
2119TEST(ConstructorDeclaration, IsImplicit) {
2120  // This one doesn't match because the constructor is not added by the
2121  // compiler (it is not needed).
2122  EXPECT_TRUE(notMatches("class Foo { };",
2123                         cxxConstructorDecl(isImplicit())));
2124  // The compiler added the implicit default constructor.
2125  EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
2126                      cxxConstructorDecl(isImplicit())));
2127  EXPECT_TRUE(matches("class Foo { Foo(){} };",
2128                      cxxConstructorDecl(unless(isImplicit()))));
2129  // The compiler added an implicit assignment operator.
2130  EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
2131                      cxxMethodDecl(isImplicit(), hasName("operator="))));
2132}
2133
2134TEST(ConstructorDeclaration, IsExplicit) {
2135  EXPECT_TRUE(matches("struct S { explicit S(int); };",
2136                      cxxConstructorDecl(isExplicit())));
2137  EXPECT_TRUE(notMatches("struct S { S(int); };",
2138                         cxxConstructorDecl(isExplicit())));
2139}
2140
2141TEST(ConstructorDeclaration, Kinds) {
2142  EXPECT_TRUE(matches("struct S { S(); };",
2143                      cxxConstructorDecl(isDefaultConstructor())));
2144  EXPECT_TRUE(notMatches("struct S { S(); };",
2145                         cxxConstructorDecl(isCopyConstructor())));
2146  EXPECT_TRUE(notMatches("struct S { S(); };",
2147                         cxxConstructorDecl(isMoveConstructor())));
2148
2149  EXPECT_TRUE(notMatches("struct S { S(const S&); };",
2150                         cxxConstructorDecl(isDefaultConstructor())));
2151  EXPECT_TRUE(matches("struct S { S(const S&); };",
2152                      cxxConstructorDecl(isCopyConstructor())));
2153  EXPECT_TRUE(notMatches("struct S { S(const S&); };",
2154                         cxxConstructorDecl(isMoveConstructor())));
2155
2156  EXPECT_TRUE(notMatches("struct S { S(S&&); };",
2157                         cxxConstructorDecl(isDefaultConstructor())));
2158  EXPECT_TRUE(notMatches("struct S { S(S&&); };",
2159                         cxxConstructorDecl(isCopyConstructor())));
2160  EXPECT_TRUE(matches("struct S { S(S&&); };",
2161                      cxxConstructorDecl(isMoveConstructor())));
2162}
2163
2164TEST(DestructorDeclaration, MatchesVirtualDestructor) {
2165  EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
2166                      cxxDestructorDecl(ofClass(hasName("Foo")))));
2167}
2168
2169TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
2170  EXPECT_TRUE(notMatches("class Foo {};",
2171                         cxxDestructorDecl(ofClass(hasName("Foo")))));
2172}
2173
2174TEST(HasAnyConstructorInitializer, SimpleCase) {
2175  EXPECT_TRUE(
2176      notMatches("class Foo { Foo() { } };",
2177                 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
2178  EXPECT_TRUE(
2179      matches("class Foo {"
2180              "  Foo() : foo_() { }"
2181              "  int foo_;"
2182              "};",
2183              cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
2184}
2185
2186TEST(HasAnyConstructorInitializer, ForField) {
2187  static const char Code[] =
2188      "class Baz { };"
2189      "class Foo {"
2190      "  Foo() : foo_() { }"
2191      "  Baz foo_;"
2192      "  Baz bar_;"
2193      "};";
2194  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
2195      forField(hasType(recordDecl(hasName("Baz"))))))));
2196  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
2197      forField(hasName("foo_"))))));
2198  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
2199      forField(hasType(recordDecl(hasName("Bar"))))))));
2200}
2201
2202TEST(HasAnyConstructorInitializer, WithInitializer) {
2203  static const char Code[] =
2204      "class Foo {"
2205      "  Foo() : foo_(0) { }"
2206      "  int foo_;"
2207      "};";
2208  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
2209      withInitializer(integerLiteral(equals(0)))))));
2210  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
2211      withInitializer(integerLiteral(equals(1)))))));
2212}
2213
2214TEST(HasAnyConstructorInitializer, IsWritten) {
2215  static const char Code[] =
2216      "struct Bar { Bar(){} };"
2217      "class Foo {"
2218      "  Foo() : foo_() { }"
2219      "  Bar foo_;"
2220      "  Bar bar_;"
2221      "};";
2222  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
2223      allOf(forField(hasName("foo_")), isWritten())))));
2224  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
2225      allOf(forField(hasName("bar_")), isWritten())))));
2226  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
2227      allOf(forField(hasName("bar_")), unless(isWritten()))))));
2228}
2229
2230TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
2231  static const char Code[] =
2232      "struct B {};"
2233      "struct D : B {"
2234      "  int I;"
2235      "  D(int i) : I(i) {}"
2236      "};"
2237      "struct E : B {"
2238      "  E() : B() {}"
2239      "};";
2240  EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
2241    hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2242    hasName("E")))));
2243  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
2244    hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2245    hasName("D")))));
2246  EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
2247    hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2248    hasName("D")))));
2249  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
2250    hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2251    hasName("E")))));
2252}
2253
2254TEST(Matcher, NewExpression) {
2255  StatementMatcher New = cxxNewExpr();
2256
2257  EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2258  EXPECT_TRUE(
2259      matches("class X { public: X(); }; void x() { new X(); }", New));
2260  EXPECT_TRUE(
2261      matches("class X { public: X(int); }; void x() { new X(0); }", New));
2262  EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2263}
2264
2265TEST(Matcher, NewExpressionArgument) {
2266  StatementMatcher New = cxxConstructExpr(
2267      hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
2268
2269  EXPECT_TRUE(
2270      matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2271              New));
2272  EXPECT_TRUE(
2273      matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2274              New));
2275  EXPECT_TRUE(
2276      notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2277                 New));
2278
2279  StatementMatcher WrongIndex = cxxConstructExpr(
2280      hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
2281  EXPECT_TRUE(
2282      notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2283                 WrongIndex));
2284}
2285
2286TEST(Matcher, NewExpressionArgumentCount) {
2287  StatementMatcher New = cxxConstructExpr(argumentCountIs(1));
2288
2289  EXPECT_TRUE(
2290      matches("class X { public: X(int); }; void x() { new X(0); }", New));
2291  EXPECT_TRUE(
2292      notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2293                 New));
2294}
2295
2296TEST(Matcher, DeleteExpression) {
2297  EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
2298                      cxxDeleteExpr()));
2299}
2300
2301TEST(Matcher, DefaultArgument) {
2302  StatementMatcher Arg = cxxDefaultArgExpr();
2303
2304  EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2305  EXPECT_TRUE(
2306      matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2307  EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2308}
2309
2310TEST(Matcher, StringLiterals) {
2311  StatementMatcher Literal = stringLiteral();
2312  EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2313  // wide string
2314  EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2315  // with escaped characters
2316  EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2317  // no matching -- though the data type is the same, there is no string literal
2318  EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2319}
2320
2321TEST(Matcher, CharacterLiterals) {
2322  StatementMatcher CharLiteral = characterLiteral();
2323  EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2324  // wide character
2325  EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2326  // wide character, Hex encoded, NOT MATCHED!
2327  EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2328  EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2329}
2330
2331TEST(Matcher, IntegerLiterals) {
2332  StatementMatcher HasIntLiteral = integerLiteral();
2333  EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2334  EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2335  EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2336  EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2337
2338  // Non-matching cases (character literals, float and double)
2339  EXPECT_TRUE(notMatches("int i = L'a';",
2340                HasIntLiteral));  // this is actually a character
2341                                  // literal cast to int
2342  EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2343  EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2344  EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2345}
2346
2347TEST(Matcher, FloatLiterals) {
2348  StatementMatcher HasFloatLiteral = floatLiteral();
2349  EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2350  EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2351  EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2352  EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2353  EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
2354  EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2355  EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2356  EXPECT_TRUE(
2357      matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
2358
2359  EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
2360  EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2361  EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2362  EXPECT_TRUE(
2363      notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
2364}
2365
2366TEST(Matcher, NullPtrLiteral) {
2367  EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
2368}
2369
2370TEST(Matcher, GNUNullExpr) {
2371  EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2372}
2373
2374TEST(Matcher, AsmStatement) {
2375  EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2376}
2377
2378TEST(Matcher, Conditions) {
2379  StatementMatcher Condition =
2380      ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
2381
2382  EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2383  EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2384  EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2385  EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2386  EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2387}
2388
2389TEST(IfStmt, ChildTraversalMatchers) {
2390  EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2391                      ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
2392  EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2393                         ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
2394  EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2395                      ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
2396  EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2397                         ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
2398}
2399
2400TEST(MatchBinaryOperator, HasOperatorName) {
2401  StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2402
2403  EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2404  EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2405}
2406
2407TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2408  StatementMatcher OperatorTrueFalse =
2409      binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
2410                     hasRHS(cxxBoolLiteral(equals(false))));
2411
2412  EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2413  EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2414  EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2415
2416  StatementMatcher OperatorIntPointer = arraySubscriptExpr(
2417      hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
2418  EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
2419  EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
2420}
2421
2422TEST(MatchBinaryOperator, HasEitherOperand) {
2423  StatementMatcher HasOperand =
2424      binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
2425
2426  EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2427  EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2428  EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2429}
2430
2431TEST(Matcher, BinaryOperatorTypes) {
2432  // Integration test that verifies the AST provides all binary operators in
2433  // a way we expect.
2434  // FIXME: Operator ','
2435  EXPECT_TRUE(
2436      matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2437  EXPECT_TRUE(
2438      matches("bool b; bool c = (b = true);",
2439              binaryOperator(hasOperatorName("="))));
2440  EXPECT_TRUE(
2441      matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2442  EXPECT_TRUE(
2443      matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2444  EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2445  EXPECT_TRUE(
2446      matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2447  EXPECT_TRUE(
2448      matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2449  EXPECT_TRUE(
2450      matches("int i = 1; int j = (i <<= 2);",
2451              binaryOperator(hasOperatorName("<<="))));
2452  EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2453  EXPECT_TRUE(
2454      matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2455  EXPECT_TRUE(
2456      matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2457  EXPECT_TRUE(
2458      matches("int i = 1; int j = (i >>= 2);",
2459              binaryOperator(hasOperatorName(">>="))));
2460  EXPECT_TRUE(
2461      matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2462  EXPECT_TRUE(
2463      matches("int i = 42; int j = (i ^= 42);",
2464              binaryOperator(hasOperatorName("^="))));
2465  EXPECT_TRUE(
2466      matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2467  EXPECT_TRUE(
2468      matches("int i = 42; int j = (i %= 42);",
2469              binaryOperator(hasOperatorName("%="))));
2470  EXPECT_TRUE(
2471      matches("bool b = 42  &23;", binaryOperator(hasOperatorName("&"))));
2472  EXPECT_TRUE(
2473      matches("bool b = true && false;",
2474              binaryOperator(hasOperatorName("&&"))));
2475  EXPECT_TRUE(
2476      matches("bool b = true; bool c = (b &= false);",
2477              binaryOperator(hasOperatorName("&="))));
2478  EXPECT_TRUE(
2479      matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2480  EXPECT_TRUE(
2481      matches("bool b = true || false;",
2482              binaryOperator(hasOperatorName("||"))));
2483  EXPECT_TRUE(
2484      matches("bool b = true; bool c = (b |= false);",
2485              binaryOperator(hasOperatorName("|="))));
2486  EXPECT_TRUE(
2487      matches("int i = 42  *23;", binaryOperator(hasOperatorName("*"))));
2488  EXPECT_TRUE(
2489      matches("int i = 42; int j = (i *= 23);",
2490              binaryOperator(hasOperatorName("*="))));
2491  EXPECT_TRUE(
2492      matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2493  EXPECT_TRUE(
2494      matches("int i = 42; int j = (i /= 23);",
2495              binaryOperator(hasOperatorName("/="))));
2496  EXPECT_TRUE(
2497      matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2498  EXPECT_TRUE(
2499      matches("int i = 42; int j = (i += 23);",
2500              binaryOperator(hasOperatorName("+="))));
2501  EXPECT_TRUE(
2502      matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2503  EXPECT_TRUE(
2504      matches("int i = 42; int j = (i -= 23);",
2505              binaryOperator(hasOperatorName("-="))));
2506  EXPECT_TRUE(
2507      matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2508              binaryOperator(hasOperatorName("->*"))));
2509  EXPECT_TRUE(
2510      matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2511              binaryOperator(hasOperatorName(".*"))));
2512
2513  // Member expressions as operators are not supported in matches.
2514  EXPECT_TRUE(
2515      notMatches("struct A { void x(A *a) { a->x(this); } };",
2516                 binaryOperator(hasOperatorName("->"))));
2517
2518  // Initializer assignments are not represented as operator equals.
2519  EXPECT_TRUE(
2520      notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2521
2522  // Array indexing is not represented as operator.
2523  EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2524
2525  // Overloaded operators do not match at all.
2526  EXPECT_TRUE(notMatches(
2527      "struct A { bool operator&&(const A &a) const { return false; } };"
2528      "void x() { A a, b; a && b; }",
2529      binaryOperator()));
2530}
2531
2532TEST(MatchUnaryOperator, HasOperatorName) {
2533  StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2534
2535  EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2536  EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2537}
2538
2539TEST(MatchUnaryOperator, HasUnaryOperand) {
2540  StatementMatcher OperatorOnFalse =
2541      unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
2542
2543  EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2544  EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2545}
2546
2547TEST(Matcher, UnaryOperatorTypes) {
2548  // Integration test that verifies the AST provides all unary operators in
2549  // a way we expect.
2550  EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2551  EXPECT_TRUE(
2552      matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2553  EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2554  EXPECT_TRUE(
2555      matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2556  EXPECT_TRUE(
2557      matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2558  EXPECT_TRUE(
2559      matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2560  EXPECT_TRUE(
2561      matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2562  EXPECT_TRUE(
2563      matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2564  EXPECT_TRUE(
2565      matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2566  EXPECT_TRUE(
2567      matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2568
2569  // We don't match conversion operators.
2570  EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2571
2572  // Function calls are not represented as operator.
2573  EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2574
2575  // Overloaded operators do not match at all.
2576  // FIXME: We probably want to add that.
2577  EXPECT_TRUE(notMatches(
2578      "struct A { bool operator!() const { return false; } };"
2579      "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2580}
2581
2582TEST(Matcher, ConditionalOperator) {
2583  StatementMatcher Conditional = conditionalOperator(
2584      hasCondition(cxxBoolLiteral(equals(true))),
2585      hasTrueExpression(cxxBoolLiteral(equals(false))));
2586
2587  EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2588  EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2589  EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2590
2591  StatementMatcher ConditionalFalse = conditionalOperator(
2592      hasFalseExpression(cxxBoolLiteral(equals(false))));
2593
2594  EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2595  EXPECT_TRUE(
2596      notMatches("void x() { true ? false : true; }", ConditionalFalse));
2597}
2598
2599TEST(ArraySubscriptMatchers, ArraySubscripts) {
2600  EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2601                      arraySubscriptExpr()));
2602  EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2603                         arraySubscriptExpr()));
2604}
2605
2606TEST(ArraySubscriptMatchers, ArrayIndex) {
2607  EXPECT_TRUE(matches(
2608      "int i[2]; void f() { i[1] = 1; }",
2609      arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2610  EXPECT_TRUE(matches(
2611      "int i[2]; void f() { 1[i] = 1; }",
2612      arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2613  EXPECT_TRUE(notMatches(
2614      "int i[2]; void f() { i[1] = 1; }",
2615      arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2616}
2617
2618TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2619  EXPECT_TRUE(matches(
2620      "int i[2]; void f() { i[1] = 2; }",
2621      arraySubscriptExpr(hasBase(implicitCastExpr(
2622          hasSourceExpression(declRefExpr()))))));
2623}
2624
2625TEST(Matcher, HasNameSupportsNamespaces) {
2626  EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2627              recordDecl(hasName("a::b::C"))));
2628  EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2629              recordDecl(hasName("::a::b::C"))));
2630  EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2631              recordDecl(hasName("b::C"))));
2632  EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2633              recordDecl(hasName("C"))));
2634  EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2635              recordDecl(hasName("c::b::C"))));
2636  EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2637              recordDecl(hasName("a::c::C"))));
2638  EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2639              recordDecl(hasName("a::b::A"))));
2640  EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2641              recordDecl(hasName("::C"))));
2642  EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2643              recordDecl(hasName("::b::C"))));
2644  EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2645              recordDecl(hasName("z::a::b::C"))));
2646  EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2647              recordDecl(hasName("a+b::C"))));
2648  EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
2649              recordDecl(hasName("C"))));
2650}
2651
2652TEST(Matcher, HasNameSupportsOuterClasses) {
2653  EXPECT_TRUE(
2654      matches("class A { class B { class C; }; };",
2655              recordDecl(hasName("A::B::C"))));
2656  EXPECT_TRUE(
2657      matches("class A { class B { class C; }; };",
2658              recordDecl(hasName("::A::B::C"))));
2659  EXPECT_TRUE(
2660      matches("class A { class B { class C; }; };",
2661              recordDecl(hasName("B::C"))));
2662  EXPECT_TRUE(
2663      matches("class A { class B { class C; }; };",
2664              recordDecl(hasName("C"))));
2665  EXPECT_TRUE(
2666      notMatches("class A { class B { class C; }; };",
2667                 recordDecl(hasName("c::B::C"))));
2668  EXPECT_TRUE(
2669      notMatches("class A { class B { class C; }; };",
2670                 recordDecl(hasName("A::c::C"))));
2671  EXPECT_TRUE(
2672      notMatches("class A { class B { class C; }; };",
2673                 recordDecl(hasName("A::B::A"))));
2674  EXPECT_TRUE(
2675      notMatches("class A { class B { class C; }; };",
2676                 recordDecl(hasName("::C"))));
2677  EXPECT_TRUE(
2678      notMatches("class A { class B { class C; }; };",
2679                 recordDecl(hasName("::B::C"))));
2680  EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2681              recordDecl(hasName("z::A::B::C"))));
2682  EXPECT_TRUE(
2683      notMatches("class A { class B { class C; }; };",
2684                 recordDecl(hasName("A+B::C"))));
2685}
2686
2687TEST(Matcher, IsDefinition) {
2688  DeclarationMatcher DefinitionOfClassA =
2689      recordDecl(hasName("A"), isDefinition());
2690  EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2691  EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2692
2693  DeclarationMatcher DefinitionOfVariableA =
2694      varDecl(hasName("a"), isDefinition());
2695  EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2696  EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2697
2698  DeclarationMatcher DefinitionOfMethodA =
2699      cxxMethodDecl(hasName("a"), isDefinition());
2700  EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2701  EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2702}
2703
2704TEST(Matcher, OfClass) {
2705  StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
2706      ofClass(hasName("X")))));
2707
2708  EXPECT_TRUE(
2709      matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2710  EXPECT_TRUE(
2711      matches("class X { public: X(); }; void x(int) { X x = X(); }",
2712              Constructor));
2713  EXPECT_TRUE(
2714      notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2715                 Constructor));
2716}
2717
2718TEST(Matcher, VisitsTemplateInstantiations) {
2719  EXPECT_TRUE(matches(
2720      "class A { public: void x(); };"
2721      "template <typename T> class B { public: void y() { T t; t.x(); } };"
2722      "void f() { B<A> b; b.y(); }",
2723      callExpr(callee(cxxMethodDecl(hasName("x"))))));
2724
2725  EXPECT_TRUE(matches(
2726      "class A { public: void x(); };"
2727      "class C {"
2728      " public:"
2729      "  template <typename T> class B { public: void y() { T t; t.x(); } };"
2730      "};"
2731      "void f() {"
2732      "  C::B<A> b; b.y();"
2733      "}",
2734      recordDecl(hasName("C"), hasDescendant(callExpr(
2735                                   callee(cxxMethodDecl(hasName("x"))))))));
2736}
2737
2738TEST(Matcher, HandlesNullQualTypes) {
2739  // FIXME: Add a Type matcher so we can replace uses of this
2740  // variable with Type(True())
2741  const TypeMatcher AnyType = anything();
2742
2743  // We don't really care whether this matcher succeeds; we're testing that
2744  // it completes without crashing.
2745  EXPECT_TRUE(matches(
2746      "struct A { };"
2747      "template <typename T>"
2748      "void f(T t) {"
2749      "  T local_t(t /* this becomes a null QualType in the AST */);"
2750      "}"
2751      "void g() {"
2752      "  f(0);"
2753      "}",
2754      expr(hasType(TypeMatcher(
2755          anyOf(
2756              TypeMatcher(hasDeclaration(anything())),
2757              pointsTo(AnyType),
2758              references(AnyType)
2759              // Other QualType matchers should go here.
2760                ))))));
2761}
2762
2763// For testing AST_MATCHER_P().
2764AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
2765  // Make sure all special variables are used: node, match_finder,
2766  // bound_nodes_builder, and the parameter named 'AMatcher'.
2767  return AMatcher.matches(Node, Finder, Builder);
2768}
2769
2770TEST(AstMatcherPMacro, Works) {
2771  DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
2772
2773  EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
2774      HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
2775
2776  EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
2777      HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
2778
2779  EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
2780      HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
2781}
2782
2783AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2784                          AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2785                          internal::Matcher<Decl>, AMatcher) {
2786  return Finder->matchesChildOf(
2787      Node, AMatcher, Builder,
2788      ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2789      ASTMatchFinder::BK_First);
2790}
2791
2792TEST(AstPolymorphicMatcherPMacro, Works) {
2793  DeclarationMatcher HasClassB =
2794      polymorphicHas(recordDecl(hasName("B")).bind("b"));
2795
2796  EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
2797      HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
2798
2799  EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
2800      HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
2801
2802  EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
2803      HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
2804
2805  StatementMatcher StatementHasClassB =
2806      polymorphicHas(recordDecl(hasName("B")));
2807
2808  EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2809}
2810
2811TEST(For, FindsForLoops) {
2812  EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2813  EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
2814  EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2815                         "void f() { for (auto &a : as); }",
2816                         forStmt()));
2817}
2818
2819TEST(For, ForLoopInternals) {
2820  EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2821                      forStmt(hasCondition(anything()))));
2822  EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2823                      forStmt(hasLoopInit(anything()))));
2824}
2825
2826TEST(For, ForRangeLoopInternals) {
2827  EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2828                      cxxForRangeStmt(hasLoopVariable(anything()))));
2829  EXPECT_TRUE(matches(
2830      "void f(){ int a[] {1, 2}; for (int i : a); }",
2831      cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
2832}
2833
2834TEST(For, NegativeForLoopInternals) {
2835  EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
2836                         forStmt(hasCondition(expr()))));
2837  EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2838                         forStmt(hasLoopInit(anything()))));
2839}
2840
2841TEST(For, ReportsNoFalsePositives) {
2842  EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2843  EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2844}
2845
2846TEST(CompoundStatement, HandlesSimpleCases) {
2847  EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2848  EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2849  EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
2850}
2851
2852TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2853  // It's not a compound statement just because there's "{}" in the source
2854  // text. This is an AST search, not grep.
2855  EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
2856              compoundStmt()));
2857  EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
2858              compoundStmt()));
2859}
2860
2861TEST(HasBody, FindsBodyOfForWhileDoLoops) {
2862  EXPECT_TRUE(matches("void f() { for(;;) {} }",
2863              forStmt(hasBody(compoundStmt()))));
2864  EXPECT_TRUE(notMatches("void f() { for(;;); }",
2865              forStmt(hasBody(compoundStmt()))));
2866  EXPECT_TRUE(matches("void f() { while(true) {} }",
2867              whileStmt(hasBody(compoundStmt()))));
2868  EXPECT_TRUE(matches("void f() { do {} while(true); }",
2869              doStmt(hasBody(compoundStmt()))));
2870  EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2871              cxxForRangeStmt(hasBody(compoundStmt()))));
2872}
2873
2874TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2875  // The simplest case: every compound statement is in a function
2876  // definition, and the function body itself must be a compound
2877  // statement.
2878  EXPECT_TRUE(matches("void f() { for (;;); }",
2879              compoundStmt(hasAnySubstatement(forStmt()))));
2880}
2881
2882TEST(HasAnySubstatement, IsNotRecursive) {
2883  // It's really "has any immediate substatement".
2884  EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
2885              compoundStmt(hasAnySubstatement(forStmt()))));
2886}
2887
2888TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2889  EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
2890              compoundStmt(hasAnySubstatement(forStmt()))));
2891}
2892
2893TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2894  EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
2895              compoundStmt(hasAnySubstatement(forStmt()))));
2896}
2897
2898TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2899  EXPECT_TRUE(matches("void f() { }",
2900              compoundStmt(statementCountIs(0))));
2901  EXPECT_TRUE(notMatches("void f() {}",
2902              compoundStmt(statementCountIs(1))));
2903}
2904
2905TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2906  EXPECT_TRUE(matches("void f() { 1; }",
2907              compoundStmt(statementCountIs(1))));
2908  EXPECT_TRUE(notMatches("void f() { 1; }",
2909              compoundStmt(statementCountIs(0))));
2910  EXPECT_TRUE(notMatches("void f() { 1; }",
2911              compoundStmt(statementCountIs(2))));
2912}
2913
2914TEST(StatementCountIs, WorksWithMultipleStatements) {
2915  EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
2916              compoundStmt(statementCountIs(3))));
2917}
2918
2919TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2920  EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2921              compoundStmt(statementCountIs(1))));
2922  EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2923              compoundStmt(statementCountIs(2))));
2924  EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
2925              compoundStmt(statementCountIs(3))));
2926  EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2927              compoundStmt(statementCountIs(4))));
2928}
2929
2930TEST(Member, WorksInSimplestCase) {
2931  EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
2932                      memberExpr(member(hasName("first")))));
2933}
2934
2935TEST(Member, DoesNotMatchTheBaseExpression) {
2936  // Don't pick out the wrong part of the member expression, this should
2937  // be checking the member (name) only.
2938  EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
2939                         memberExpr(member(hasName("first")))));
2940}
2941
2942TEST(Member, MatchesInMemberFunctionCall) {
2943  EXPECT_TRUE(matches("void f() {"
2944                      "  struct { void first() {}; } s;"
2945                      "  s.first();"
2946                      "};",
2947                      memberExpr(member(hasName("first")))));
2948}
2949
2950TEST(Member, MatchesMember) {
2951  EXPECT_TRUE(matches(
2952      "struct A { int i; }; void f() { A a; a.i = 2; }",
2953      memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2954  EXPECT_TRUE(notMatches(
2955      "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2956      memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2957}
2958
2959TEST(Member, UnderstandsAccess) {
2960  EXPECT_TRUE(matches(
2961      "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2962  EXPECT_TRUE(notMatches(
2963      "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2964  EXPECT_TRUE(notMatches(
2965      "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2966
2967  EXPECT_TRUE(notMatches(
2968      "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2969  EXPECT_TRUE(notMatches(
2970      "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2971  EXPECT_TRUE(matches(
2972      "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2973
2974  EXPECT_TRUE(notMatches(
2975      "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2976  EXPECT_TRUE(matches("class A { protected: int i; };",
2977                      fieldDecl(isProtected(), hasName("i"))));
2978  EXPECT_TRUE(notMatches(
2979      "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2980
2981  // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2982  EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2983  EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2984  EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2985}
2986
2987TEST(Member, MatchesMemberAllocationFunction) {
2988  // Fails in C++11 mode
2989  EXPECT_TRUE(matchesConditionally(
2990      "namespace std { typedef typeof(sizeof(int)) size_t; }"
2991      "class X { void *operator new(std::size_t); };",
2992      cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
2993
2994  EXPECT_TRUE(matches("class X { void operator delete(void*); };",
2995                      cxxMethodDecl(ofClass(hasName("X")))));
2996
2997  // Fails in C++11 mode
2998  EXPECT_TRUE(matchesConditionally(
2999      "namespace std { typedef typeof(sizeof(int)) size_t; }"
3000      "class X { void operator delete[](void*, std::size_t); };",
3001      cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
3002}
3003
3004TEST(HasObjectExpression, DoesNotMatchMember) {
3005  EXPECT_TRUE(notMatches(
3006      "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
3007      memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
3008}
3009
3010TEST(HasObjectExpression, MatchesBaseOfVariable) {
3011  EXPECT_TRUE(matches(
3012      "struct X { int m; }; void f(X x) { x.m; }",
3013      memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
3014  EXPECT_TRUE(matches(
3015      "struct X { int m; }; void f(X* x) { x->m; }",
3016      memberExpr(hasObjectExpression(
3017          hasType(pointsTo(recordDecl(hasName("X"))))))));
3018}
3019
3020TEST(HasObjectExpression,
3021     MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
3022  EXPECT_TRUE(matches(
3023      "class X {}; struct S { X m; void f() { this->m; } };",
3024      memberExpr(hasObjectExpression(
3025          hasType(pointsTo(recordDecl(hasName("S"))))))));
3026  EXPECT_TRUE(matches(
3027      "class X {}; struct S { X m; void f() { m; } };",
3028      memberExpr(hasObjectExpression(
3029          hasType(pointsTo(recordDecl(hasName("S"))))))));
3030}
3031
3032TEST(Field, DoesNotMatchNonFieldMembers) {
3033  EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
3034  EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
3035  EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
3036  EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
3037}
3038
3039TEST(Field, MatchesField) {
3040  EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
3041}
3042
3043TEST(IsVolatileQualified, QualifiersMatch) {
3044  EXPECT_TRUE(matches("volatile int i = 42;",
3045                      varDecl(hasType(isVolatileQualified()))));
3046  EXPECT_TRUE(notMatches("volatile int *i;",
3047                         varDecl(hasType(isVolatileQualified()))));
3048  EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
3049                      varDecl(hasType(isVolatileQualified()))));
3050}
3051
3052TEST(IsConstQualified, MatchesConstInt) {
3053  EXPECT_TRUE(matches("const int i = 42;",
3054                      varDecl(hasType(isConstQualified()))));
3055}
3056
3057TEST(IsConstQualified, MatchesConstPointer) {
3058  EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
3059                      varDecl(hasType(isConstQualified()))));
3060}
3061
3062TEST(IsConstQualified, MatchesThroughTypedef) {
3063  EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
3064                      varDecl(hasType(isConstQualified()))));
3065  EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
3066                      varDecl(hasType(isConstQualified()))));
3067}
3068
3069TEST(IsConstQualified, DoesNotMatchInappropriately) {
3070  EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
3071                         varDecl(hasType(isConstQualified()))));
3072  EXPECT_TRUE(notMatches("int const* p;",
3073                         varDecl(hasType(isConstQualified()))));
3074}
3075
3076TEST(CastExpression, MatchesExplicitCasts) {
3077  EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
3078  EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
3079  EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
3080  EXPECT_TRUE(matches("char c = char(0);", castExpr()));
3081}
3082TEST(CastExpression, MatchesImplicitCasts) {
3083  // This test creates an implicit cast from int to char.
3084  EXPECT_TRUE(matches("char c = 0;", castExpr()));
3085  // This test creates an implicit cast from lvalue to rvalue.
3086  EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
3087}
3088
3089TEST(CastExpression, DoesNotMatchNonCasts) {
3090  EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
3091  EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
3092  EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
3093  EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
3094}
3095
3096TEST(ReinterpretCast, MatchesSimpleCase) {
3097  EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
3098                      cxxReinterpretCastExpr()));
3099}
3100
3101TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
3102  EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
3103  EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
3104                         cxxReinterpretCastExpr()));
3105  EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
3106                         cxxReinterpretCastExpr()));
3107  EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3108                         "B b;"
3109                         "D* p = dynamic_cast<D*>(&b);",
3110                         cxxReinterpretCastExpr()));
3111}
3112
3113TEST(FunctionalCast, MatchesSimpleCase) {
3114  std::string foo_class = "class Foo { public: Foo(const char*); };";
3115  EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
3116                      cxxFunctionalCastExpr()));
3117}
3118
3119TEST(FunctionalCast, DoesNotMatchOtherCasts) {
3120  std::string FooClass = "class Foo { public: Foo(const char*); };";
3121  EXPECT_TRUE(
3122      notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
3123                 cxxFunctionalCastExpr()));
3124  EXPECT_TRUE(
3125      notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
3126                 cxxFunctionalCastExpr()));
3127}
3128
3129TEST(DynamicCast, MatchesSimpleCase) {
3130  EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
3131                      "B b;"
3132                      "D* p = dynamic_cast<D*>(&b);",
3133                      cxxDynamicCastExpr()));
3134}
3135
3136TEST(StaticCast, MatchesSimpleCase) {
3137  EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
3138                      cxxStaticCastExpr()));
3139}
3140
3141TEST(StaticCast, DoesNotMatchOtherCasts) {
3142  EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
3143  EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
3144                         cxxStaticCastExpr()));
3145  EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
3146                         cxxStaticCastExpr()));
3147  EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3148                         "B b;"
3149                         "D* p = dynamic_cast<D*>(&b);",
3150                         cxxStaticCastExpr()));
3151}
3152
3153TEST(CStyleCast, MatchesSimpleCase) {
3154  EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
3155}
3156
3157TEST(CStyleCast, DoesNotMatchOtherCasts) {
3158  EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
3159                         "char q, *r = const_cast<char*>(&q);"
3160                         "void* s = reinterpret_cast<char*>(&s);"
3161                         "struct B { virtual ~B() {} }; struct D : B {};"
3162                         "B b;"
3163                         "D* t = dynamic_cast<D*>(&b);",
3164                         cStyleCastExpr()));
3165}
3166
3167TEST(HasDestinationType, MatchesSimpleCase) {
3168  EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
3169                      cxxStaticCastExpr(hasDestinationType(
3170                          pointsTo(TypeMatcher(anything()))))));
3171}
3172
3173TEST(HasImplicitDestinationType, MatchesSimpleCase) {
3174  // This test creates an implicit const cast.
3175  EXPECT_TRUE(matches("int x; const int i = x;",
3176                      implicitCastExpr(
3177                          hasImplicitDestinationType(isInteger()))));
3178  // This test creates an implicit array-to-pointer cast.
3179  EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
3180                      implicitCastExpr(hasImplicitDestinationType(
3181                          pointsTo(TypeMatcher(anything()))))));
3182}
3183
3184TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
3185  // This test creates an implicit cast from int to char.
3186  EXPECT_TRUE(notMatches("char c = 0;",
3187                      implicitCastExpr(hasImplicitDestinationType(
3188                          unless(anything())))));
3189  // This test creates an implicit array-to-pointer cast.
3190  EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
3191                      implicitCastExpr(hasImplicitDestinationType(
3192                          unless(anything())))));
3193}
3194
3195TEST(ImplicitCast, MatchesSimpleCase) {
3196  // This test creates an implicit const cast.
3197  EXPECT_TRUE(matches("int x = 0; const int y = x;",
3198                      varDecl(hasInitializer(implicitCastExpr()))));
3199  // This test creates an implicit cast from int to char.
3200  EXPECT_TRUE(matches("char c = 0;",
3201                      varDecl(hasInitializer(implicitCastExpr()))));
3202  // This test creates an implicit array-to-pointer cast.
3203  EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
3204                      varDecl(hasInitializer(implicitCastExpr()))));
3205}
3206
3207TEST(ImplicitCast, DoesNotMatchIncorrectly) {
3208  // This test verifies that implicitCastExpr() matches exactly when implicit casts
3209  // are present, and that it ignores explicit and paren casts.
3210
3211  // These two test cases have no casts.
3212  EXPECT_TRUE(notMatches("int x = 0;",
3213                         varDecl(hasInitializer(implicitCastExpr()))));
3214  EXPECT_TRUE(notMatches("int x = 0, &y = x;",
3215                         varDecl(hasInitializer(implicitCastExpr()))));
3216
3217  EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
3218                         varDecl(hasInitializer(implicitCastExpr()))));
3219  EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
3220                         varDecl(hasInitializer(implicitCastExpr()))));
3221
3222  EXPECT_TRUE(notMatches("int x = (0);",
3223                         varDecl(hasInitializer(implicitCastExpr()))));
3224}
3225
3226TEST(IgnoringImpCasts, MatchesImpCasts) {
3227  // This test checks that ignoringImpCasts matches when implicit casts are
3228  // present and its inner matcher alone does not match.
3229  // Note that this test creates an implicit const cast.
3230  EXPECT_TRUE(matches("int x = 0; const int y = x;",
3231                      varDecl(hasInitializer(ignoringImpCasts(
3232                          declRefExpr(to(varDecl(hasName("x")))))))));
3233  // This test creates an implict cast from int to char.
3234  EXPECT_TRUE(matches("char x = 0;",
3235                      varDecl(hasInitializer(ignoringImpCasts(
3236                          integerLiteral(equals(0)))))));
3237}
3238
3239TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3240  // These tests verify that ignoringImpCasts does not match if the inner
3241  // matcher does not match.
3242  // Note that the first test creates an implicit const cast.
3243  EXPECT_TRUE(notMatches("int x; const int y = x;",
3244                         varDecl(hasInitializer(ignoringImpCasts(
3245                             unless(anything()))))));
3246  EXPECT_TRUE(notMatches("int x; int y = x;",
3247                         varDecl(hasInitializer(ignoringImpCasts(
3248                             unless(anything()))))));
3249
3250  // These tests verify that ignoringImplictCasts does not look through explicit
3251  // casts or parentheses.
3252  EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
3253                         varDecl(hasInitializer(ignoringImpCasts(
3254                             integerLiteral())))));
3255  EXPECT_TRUE(notMatches("int i = (0);",
3256                         varDecl(hasInitializer(ignoringImpCasts(
3257                             integerLiteral())))));
3258  EXPECT_TRUE(notMatches("float i = (float)0;",
3259                         varDecl(hasInitializer(ignoringImpCasts(
3260                             integerLiteral())))));
3261  EXPECT_TRUE(notMatches("float i = float(0);",
3262                         varDecl(hasInitializer(ignoringImpCasts(
3263                             integerLiteral())))));
3264}
3265
3266TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3267  // This test verifies that expressions that do not have implicit casts
3268  // still match the inner matcher.
3269  EXPECT_TRUE(matches("int x = 0; int &y = x;",
3270                      varDecl(hasInitializer(ignoringImpCasts(
3271                          declRefExpr(to(varDecl(hasName("x")))))))));
3272}
3273
3274TEST(IgnoringParenCasts, MatchesParenCasts) {
3275  // This test checks that ignoringParenCasts matches when parentheses and/or
3276  // casts are present and its inner matcher alone does not match.
3277  EXPECT_TRUE(matches("int x = (0);",
3278                      varDecl(hasInitializer(ignoringParenCasts(
3279                          integerLiteral(equals(0)))))));
3280  EXPECT_TRUE(matches("int x = (((((0)))));",
3281                      varDecl(hasInitializer(ignoringParenCasts(
3282                          integerLiteral(equals(0)))))));
3283
3284  // This test creates an implict cast from int to char in addition to the
3285  // parentheses.
3286  EXPECT_TRUE(matches("char x = (0);",
3287                      varDecl(hasInitializer(ignoringParenCasts(
3288                          integerLiteral(equals(0)))))));
3289
3290  EXPECT_TRUE(matches("char x = (char)0;",
3291                      varDecl(hasInitializer(ignoringParenCasts(
3292                          integerLiteral(equals(0)))))));
3293  EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
3294                      varDecl(hasInitializer(ignoringParenCasts(
3295                          integerLiteral(equals(0)))))));
3296}
3297
3298TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3299  // This test verifies that expressions that do not have any casts still match.
3300  EXPECT_TRUE(matches("int x = 0;",
3301                      varDecl(hasInitializer(ignoringParenCasts(
3302                          integerLiteral(equals(0)))))));
3303}
3304
3305TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3306  // These tests verify that ignoringImpCasts does not match if the inner
3307  // matcher does not match.
3308  EXPECT_TRUE(notMatches("int x = ((0));",
3309                         varDecl(hasInitializer(ignoringParenCasts(
3310                             unless(anything()))))));
3311
3312  // This test creates an implicit cast from int to char in addition to the
3313  // parentheses.
3314  EXPECT_TRUE(notMatches("char x = ((0));",
3315                         varDecl(hasInitializer(ignoringParenCasts(
3316                             unless(anything()))))));
3317
3318  EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
3319                         varDecl(hasInitializer(ignoringParenCasts(
3320                             unless(anything()))))));
3321}
3322
3323TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3324  // This test checks that ignoringParenAndImpCasts matches when
3325  // parentheses and/or implicit casts are present and its inner matcher alone
3326  // does not match.
3327  // Note that this test creates an implicit const cast.
3328  EXPECT_TRUE(matches("int x = 0; const int y = x;",
3329                      varDecl(hasInitializer(ignoringParenImpCasts(
3330                          declRefExpr(to(varDecl(hasName("x")))))))));
3331  // This test creates an implicit cast from int to char.
3332  EXPECT_TRUE(matches("const char x = (0);",
3333                      varDecl(hasInitializer(ignoringParenImpCasts(
3334                          integerLiteral(equals(0)))))));
3335}
3336
3337TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3338  // This test verifies that expressions that do not have parentheses or
3339  // implicit casts still match.
3340  EXPECT_TRUE(matches("int x = 0; int &y = x;",
3341                      varDecl(hasInitializer(ignoringParenImpCasts(
3342                          declRefExpr(to(varDecl(hasName("x")))))))));
3343  EXPECT_TRUE(matches("int x = 0;",
3344                      varDecl(hasInitializer(ignoringParenImpCasts(
3345                          integerLiteral(equals(0)))))));
3346}
3347
3348TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3349  // These tests verify that ignoringParenImpCasts does not match if
3350  // the inner matcher does not match.
3351  // This test creates an implicit cast.
3352  EXPECT_TRUE(notMatches("char c = ((3));",
3353                         varDecl(hasInitializer(ignoringParenImpCasts(
3354                             unless(anything()))))));
3355  // These tests verify that ignoringParenAndImplictCasts does not look
3356  // through explicit casts.
3357  EXPECT_TRUE(notMatches("float y = (float(0));",
3358                         varDecl(hasInitializer(ignoringParenImpCasts(
3359                             integerLiteral())))));
3360  EXPECT_TRUE(notMatches("float y = (float)0;",
3361                         varDecl(hasInitializer(ignoringParenImpCasts(
3362                             integerLiteral())))));
3363  EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
3364                         varDecl(hasInitializer(ignoringParenImpCasts(
3365                             integerLiteral())))));
3366}
3367
3368TEST(HasSourceExpression, MatchesImplicitCasts) {
3369  EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3370                      "void r() {string a_string; URL url = a_string; }",
3371                      implicitCastExpr(
3372                          hasSourceExpression(cxxConstructExpr()))));
3373}
3374
3375TEST(HasSourceExpression, MatchesExplicitCasts) {
3376  EXPECT_TRUE(matches("float x = static_cast<float>(42);",
3377                      explicitCastExpr(
3378                          hasSourceExpression(hasDescendant(
3379                              expr(integerLiteral()))))));
3380}
3381
3382TEST(Statement, DoesNotMatchDeclarations) {
3383  EXPECT_TRUE(notMatches("class X {};", stmt()));
3384}
3385
3386TEST(Statement, MatchesCompoundStatments) {
3387  EXPECT_TRUE(matches("void x() {}", stmt()));
3388}
3389
3390TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
3391  EXPECT_TRUE(notMatches("void x() {}", declStmt()));
3392}
3393
3394TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
3395  EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
3396}
3397
3398TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3399  EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3400                      "const Foo f = Foo();",
3401                      varDecl(hasInitializer(exprWithCleanups()))));
3402  EXPECT_FALSE(matches("struct Foo { };"
3403                      "const Foo f = Foo();",
3404                      varDecl(hasInitializer(exprWithCleanups()))));
3405}
3406
3407TEST(InitListExpression, MatchesInitListExpression) {
3408  EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3409                      initListExpr(hasType(asString("int [2]")))));
3410  EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
3411                      initListExpr(hasType(recordDecl(hasName("B"))))));
3412  EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3413                      "void f();"
3414                      "S s[1] = { &f };",
3415                      declRefExpr(to(functionDecl(hasName("f"))))));
3416  EXPECT_TRUE(
3417      matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
3418}
3419
3420TEST(UsingDeclaration, MatchesUsingDeclarations) {
3421  EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3422                      usingDecl()));
3423}
3424
3425TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3426  EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3427                      usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3428}
3429
3430TEST(UsingDeclaration, MatchesSpecificTarget) {
3431  EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3432                      usingDecl(hasAnyUsingShadowDecl(
3433                          hasTargetDecl(functionDecl())))));
3434  EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3435                         usingDecl(hasAnyUsingShadowDecl(
3436                             hasTargetDecl(functionDecl())))));
3437}
3438
3439TEST(UsingDeclaration, ThroughUsingDeclaration) {
3440  EXPECT_TRUE(matches(
3441      "namespace a { void f(); } using a::f; void g() { f(); }",
3442      declRefExpr(throughUsingDecl(anything()))));
3443  EXPECT_TRUE(notMatches(
3444      "namespace a { void f(); } using a::f; void g() { a::f(); }",
3445      declRefExpr(throughUsingDecl(anything()))));
3446}
3447
3448TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3449  EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3450                      usingDirectiveDecl()));
3451  EXPECT_FALSE(
3452      matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3453}
3454
3455TEST(SingleDecl, IsSingleDecl) {
3456  StatementMatcher SingleDeclStmt =
3457      declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
3458  EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3459  EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3460  EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3461                          SingleDeclStmt));
3462}
3463
3464TEST(DeclStmt, ContainsDeclaration) {
3465  DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
3466
3467  EXPECT_TRUE(matches("void f() {int a = 4;}",
3468                      declStmt(containsDeclaration(0, MatchesInit))));
3469  EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
3470                      declStmt(containsDeclaration(0, MatchesInit),
3471                               containsDeclaration(1, MatchesInit))));
3472  unsigned WrongIndex = 42;
3473  EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3474                         declStmt(containsDeclaration(WrongIndex,
3475                                                      MatchesInit))));
3476}
3477
3478TEST(DeclCount, DeclCountIsCorrect) {
3479  EXPECT_TRUE(matches("void f() {int i,j;}",
3480                      declStmt(declCountIs(2))));
3481  EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
3482                         declStmt(declCountIs(3))));
3483  EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
3484                         declStmt(declCountIs(3))));
3485}
3486
3487TEST(While, MatchesWhileLoops) {
3488  EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3489  EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3490  EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3491}
3492
3493TEST(Do, MatchesDoLoops) {
3494  EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3495  EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3496}
3497
3498TEST(Do, DoesNotMatchWhileLoops) {
3499  EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3500}
3501
3502TEST(SwitchCase, MatchesCase) {
3503  EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3504  EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3505  EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3506  EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3507}
3508
3509TEST(SwitchCase, MatchesSwitch) {
3510  EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3511  EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3512  EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3513  EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3514}
3515
3516TEST(SwitchCase, MatchesEachCase) {
3517  EXPECT_TRUE(notMatches("void x() { switch(42); }",
3518                         switchStmt(forEachSwitchCase(caseStmt()))));
3519  EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3520                      switchStmt(forEachSwitchCase(caseStmt()))));
3521  EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3522                      switchStmt(forEachSwitchCase(caseStmt()))));
3523  EXPECT_TRUE(notMatches(
3524      "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3525      ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3526  EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3527                      switchStmt(forEachSwitchCase(
3528                          caseStmt(hasCaseConstant(integerLiteral()))))));
3529  EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3530                         switchStmt(forEachSwitchCase(
3531                             caseStmt(hasCaseConstant(integerLiteral()))))));
3532  EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3533                         switchStmt(forEachSwitchCase(
3534                             caseStmt(hasCaseConstant(integerLiteral()))))));
3535  EXPECT_TRUE(matchAndVerifyResultTrue(
3536      "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3537      switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3538      new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3539}
3540
3541TEST(ForEachConstructorInitializer, MatchesInitializers) {
3542  EXPECT_TRUE(matches(
3543      "struct X { X() : i(42), j(42) {} int i, j; };",
3544      cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer()))));
3545}
3546
3547TEST(ExceptionHandling, SimpleCases) {
3548  EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
3549  EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
3550  EXPECT_TRUE(
3551      notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
3552  EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3553                      cxxThrowExpr()));
3554  EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3555                      cxxThrowExpr()));
3556  EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
3557                      cxxCatchStmt(isCatchAll())));
3558  EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
3559                         cxxCatchStmt(isCatchAll())));
3560  EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3561                      varDecl(isExceptionVariable())));
3562  EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3563                         varDecl(isExceptionVariable())));
3564}
3565
3566TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3567  EXPECT_TRUE(notMatches(
3568      "void x() { if(true) {} }",
3569      ifStmt(hasConditionVariableStatement(declStmt()))));
3570  EXPECT_TRUE(notMatches(
3571      "void x() { int x; if((x = 42)) {} }",
3572      ifStmt(hasConditionVariableStatement(declStmt()))));
3573}
3574
3575TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3576  EXPECT_TRUE(matches(
3577      "void x() { if(int* a = 0) {} }",
3578      ifStmt(hasConditionVariableStatement(declStmt()))));
3579}
3580
3581TEST(ForEach, BindsOneNode) {
3582  EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
3583      recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
3584      new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
3585}
3586
3587TEST(ForEach, BindsMultipleNodes) {
3588  EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
3589      recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
3590      new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
3591}
3592
3593TEST(ForEach, BindsRecursiveCombinations) {
3594  EXPECT_TRUE(matchAndVerifyResultTrue(
3595      "class C { class D { int x; int y; }; class E { int y; int z; }; };",
3596      recordDecl(hasName("C"),
3597                 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
3598      new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
3599}
3600
3601TEST(ForEachDescendant, BindsOneNode) {
3602  EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
3603      recordDecl(hasName("C"),
3604                 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
3605      new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
3606}
3607
3608TEST(ForEachDescendant, NestedForEachDescendant) {
3609  DeclarationMatcher m = recordDecl(
3610      isDefinition(), decl().bind("x"), hasName("C"));
3611  EXPECT_TRUE(matchAndVerifyResultTrue(
3612    "class A { class B { class C {}; }; };",
3613    recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3614    new VerifyIdIsBoundTo<Decl>("x", "C")));
3615
3616  // Check that a partial match of 'm' that binds 'x' in the
3617  // first part of anyOf(m, anything()) will not overwrite the
3618  // binding created by the earlier binding in the hasDescendant.
3619  EXPECT_TRUE(matchAndVerifyResultTrue(
3620      "class A { class B { class C {}; }; };",
3621      recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3622      new VerifyIdIsBoundTo<Decl>("x", "C")));
3623}
3624
3625TEST(ForEachDescendant, BindsMultipleNodes) {
3626  EXPECT_TRUE(matchAndVerifyResultTrue(
3627      "class C { class D { int x; int y; }; "
3628      "          class E { class F { int y; int z; }; }; };",
3629      recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
3630      new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
3631}
3632
3633TEST(ForEachDescendant, BindsRecursiveCombinations) {
3634  EXPECT_TRUE(matchAndVerifyResultTrue(
3635      "class C { class D { "
3636      "          class E { class F { class G { int y; int z; }; }; }; }; };",
3637      recordDecl(hasName("C"), forEachDescendant(recordDecl(
3638          forEachDescendant(fieldDecl().bind("f"))))),
3639      new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
3640}
3641
3642TEST(ForEachDescendant, BindsCombinations) {
3643  EXPECT_TRUE(matchAndVerifyResultTrue(
3644      "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3645      "(true) {} }",
3646      compoundStmt(forEachDescendant(ifStmt().bind("if")),
3647                   forEachDescendant(whileStmt().bind("while"))),
3648      new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3649}
3650
3651TEST(Has, DoesNotDeleteBindings) {
3652  EXPECT_TRUE(matchAndVerifyResultTrue(
3653      "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3654      new VerifyIdIsBoundTo<Decl>("x", 1)));
3655}
3656
3657TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3658  // Those matchers cover all the cases where an inner matcher is called
3659  // and there is not a 1:1 relationship between the match of the outer
3660  // matcher and the match of the inner matcher.
3661  // The pattern to look for is:
3662  //   ... return InnerMatcher.matches(...); ...
3663  // In which case no special handling is needed.
3664  //
3665  // On the other hand, if there are multiple alternative matches
3666  // (for example forEach*) or matches might be discarded (for example has*)
3667  // the implementation must make sure that the discarded matches do not
3668  // affect the bindings.
3669  // When new such matchers are added, add a test here that:
3670  // - matches a simple node, and binds it as the first thing in the matcher:
3671  //     recordDecl(decl().bind("x"), hasName("X")))
3672  // - uses the matcher under test afterwards in a way that not the first
3673  //   alternative is matched; for anyOf, that means the first branch
3674  //   would need to return false; for hasAncestor, it means that not
3675  //   the direct parent matches the inner matcher.
3676
3677  EXPECT_TRUE(matchAndVerifyResultTrue(
3678      "class X { int y; };",
3679      recordDecl(
3680          recordDecl().bind("x"), hasName("::X"),
3681          anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3682      new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3683  EXPECT_TRUE(matchAndVerifyResultTrue(
3684      "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3685                                anyOf(unless(anything()), anything())),
3686      new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3687  EXPECT_TRUE(matchAndVerifyResultTrue(
3688      "template<typename T1, typename T2> class X {}; X<float, int> x;",
3689      classTemplateSpecializationDecl(
3690          decl().bind("x"),
3691          hasAnyTemplateArgument(refersToType(asString("int")))),
3692      new VerifyIdIsBoundTo<Decl>("x", 1)));
3693  EXPECT_TRUE(matchAndVerifyResultTrue(
3694      "class X { void f(); void g(); };",
3695      cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3696      new VerifyIdIsBoundTo<Decl>("x", 1)));
3697  EXPECT_TRUE(matchAndVerifyResultTrue(
3698      "class X { X() : a(1), b(2) {} double a; int b; };",
3699      recordDecl(decl().bind("x"),
3700                 has(cxxConstructorDecl(
3701                     hasAnyConstructorInitializer(forField(hasName("b")))))),
3702      new VerifyIdIsBoundTo<Decl>("x", 1)));
3703  EXPECT_TRUE(matchAndVerifyResultTrue(
3704      "void x(int, int) { x(0, 42); }",
3705      callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3706      new VerifyIdIsBoundTo<Expr>("x", 1)));
3707  EXPECT_TRUE(matchAndVerifyResultTrue(
3708      "void x(int, int y) {}",
3709      functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3710      new VerifyIdIsBoundTo<Decl>("x", 1)));
3711  EXPECT_TRUE(matchAndVerifyResultTrue(
3712      "void x() { return; if (true) {} }",
3713      functionDecl(decl().bind("x"),
3714                   has(compoundStmt(hasAnySubstatement(ifStmt())))),
3715      new VerifyIdIsBoundTo<Decl>("x", 1)));
3716  EXPECT_TRUE(matchAndVerifyResultTrue(
3717      "namespace X { void b(int); void b(); }"
3718      "using X::b;",
3719      usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3720                                      functionDecl(parameterCountIs(1))))),
3721      new VerifyIdIsBoundTo<Decl>("x", 1)));
3722  EXPECT_TRUE(matchAndVerifyResultTrue(
3723      "class A{}; class B{}; class C : B, A {};",
3724      cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")),
3725      new VerifyIdIsBoundTo<Decl>("x", 1)));
3726  EXPECT_TRUE(matchAndVerifyResultTrue(
3727      "class A{}; typedef A B; typedef A C; typedef A D;"
3728      "class E : A {};",
3729      cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")),
3730      new VerifyIdIsBoundTo<Decl>("x", 1)));
3731  EXPECT_TRUE(matchAndVerifyResultTrue(
3732      "class A { class B { void f() {} }; };",
3733      functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3734      new VerifyIdIsBoundTo<Decl>("x", 1)));
3735  EXPECT_TRUE(matchAndVerifyResultTrue(
3736      "template <typename T> struct A { struct B {"
3737      "  void f() { if(true) {} }"
3738      "}; };"
3739      "void t() { A<int>::B b; b.f(); }",
3740      ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3741      new VerifyIdIsBoundTo<Stmt>("x", 2)));
3742  EXPECT_TRUE(matchAndVerifyResultTrue(
3743      "class A {};",
3744      recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3745      new VerifyIdIsBoundTo<Decl>("x", 1)));
3746  EXPECT_TRUE(matchAndVerifyResultTrue(
3747      "class A { A() : s(), i(42) {} const char *s; int i; };",
3748      cxxConstructorDecl(hasName("::A::A"), decl().bind("x"),
3749                         forEachConstructorInitializer(forField(hasName("i")))),
3750      new VerifyIdIsBoundTo<Decl>("x", 1)));
3751}
3752
3753TEST(ForEachDescendant, BindsCorrectNodes) {
3754  EXPECT_TRUE(matchAndVerifyResultTrue(
3755      "class C { void f(); int i; };",
3756      recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3757      new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3758  EXPECT_TRUE(matchAndVerifyResultTrue(
3759      "class C { void f() {} int i; };",
3760      recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3761      new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3762}
3763
3764TEST(FindAll, BindsNodeOnMatch) {
3765  EXPECT_TRUE(matchAndVerifyResultTrue(
3766      "class A {};",
3767      recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3768      new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3769}
3770
3771TEST(FindAll, BindsDescendantNodeOnMatch) {
3772  EXPECT_TRUE(matchAndVerifyResultTrue(
3773      "class A { int a; int b; };",
3774      recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3775      new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3776}
3777
3778TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3779  EXPECT_TRUE(matchAndVerifyResultTrue(
3780      "class A { int a; int b; };",
3781      recordDecl(hasName("::A"),
3782                 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3783                                    fieldDecl().bind("v"))))),
3784      new VerifyIdIsBoundTo<Decl>("v", 3)));
3785
3786  EXPECT_TRUE(matchAndVerifyResultTrue(
3787      "class A { class B {}; class C {}; };",
3788      recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3789      new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3790}
3791
3792TEST(EachOf, TriggersForEachMatch) {
3793  EXPECT_TRUE(matchAndVerifyResultTrue(
3794      "class A { int a; int b; };",
3795      recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3796                        has(fieldDecl(hasName("b")).bind("v")))),
3797      new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3798}
3799
3800TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3801  EXPECT_TRUE(matchAndVerifyResultTrue(
3802      "class A { int a; int c; };",
3803      recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3804                        has(fieldDecl(hasName("b")).bind("v")))),
3805      new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3806  EXPECT_TRUE(matchAndVerifyResultTrue(
3807      "class A { int c; int b; };",
3808      recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3809                        has(fieldDecl(hasName("b")).bind("v")))),
3810      new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3811  EXPECT_TRUE(notMatches(
3812      "class A { int c; int d; };",
3813      recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3814                        has(fieldDecl(hasName("b")).bind("v"))))));
3815}
3816
3817TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3818  // Make sure that we can both match the class by name (::X) and by the type
3819  // the template was instantiated with (via a field).
3820
3821  EXPECT_TRUE(matches(
3822      "template <typename T> class X {}; class A {}; X<A> x;",
3823      cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
3824
3825  EXPECT_TRUE(matches(
3826      "template <typename T> class X { T t; }; class A {}; X<A> x;",
3827      cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
3828          fieldDecl(hasType(recordDecl(hasName("A"))))))));
3829}
3830
3831TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3832  EXPECT_TRUE(matches(
3833      "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
3834      functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
3835               isTemplateInstantiation())));
3836}
3837
3838TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3839  EXPECT_TRUE(matches(
3840      "template <typename T> class X { T t; }; class A {};"
3841      "template class X<A>;",
3842      cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
3843          fieldDecl(hasType(recordDecl(hasName("A"))))))));
3844}
3845
3846TEST(IsTemplateInstantiation,
3847     MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3848  EXPECT_TRUE(matches(
3849      "template <typename T> class X {};"
3850      "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
3851      cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
3852}
3853
3854TEST(IsTemplateInstantiation,
3855     MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3856  EXPECT_TRUE(matches(
3857      "class A {};"
3858      "class X {"
3859      "  template <typename U> class Y { U u; };"
3860      "  Y<A> y;"
3861      "};",
3862      cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
3863}
3864
3865TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3866  // FIXME: Figure out whether this makes sense. It doesn't affect the
3867  // normal use case as long as the uppermost instantiation always is marked
3868  // as template instantiation, but it might be confusing as a predicate.
3869  EXPECT_TRUE(matches(
3870      "class A {};"
3871      "template <typename T> class X {"
3872      "  template <typename U> class Y { U u; };"
3873      "  Y<T> y;"
3874      "}; X<A> x;",
3875      cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
3876}
3877
3878TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3879  EXPECT_TRUE(notMatches(
3880      "template <typename T> class X {}; class A {};"
3881      "template <> class X<A> {}; X<A> x;",
3882      cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
3883}
3884
3885TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3886  EXPECT_TRUE(notMatches(
3887      "class A {}; class Y { A a; };",
3888      cxxRecordDecl(isTemplateInstantiation())));
3889}
3890
3891TEST(IsInstantiated, MatchesInstantiation) {
3892  EXPECT_TRUE(
3893      matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3894              cxxRecordDecl(isInstantiated())));
3895}
3896
3897TEST(IsInstantiated, NotMatchesDefinition) {
3898  EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3899                         cxxRecordDecl(isInstantiated())));
3900}
3901
3902TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3903  EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3904                      "class Y { A<int> a; }; Y y;",
3905                      declStmt(isInTemplateInstantiation())));
3906}
3907
3908TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3909  EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3910                         declStmt(isInTemplateInstantiation())));
3911}
3912
3913TEST(IsInstantiated, MatchesFunctionInstantiation) {
3914  EXPECT_TRUE(
3915      matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3916              functionDecl(isInstantiated())));
3917}
3918
3919TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3920  EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3921                         varDecl(isInstantiated())));
3922}
3923
3924TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3925  EXPECT_TRUE(
3926      matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3927              declStmt(isInTemplateInstantiation())));
3928}
3929
3930TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3931  EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3932                         declStmt(isInTemplateInstantiation())));
3933}
3934
3935TEST(IsInTemplateInstantiation, Sharing) {
3936  auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3937  // FIXME: Node sharing is an implementation detail, exposing it is ugly
3938  // and makes the matcher behave in non-obvious ways.
3939  EXPECT_TRUE(notMatches(
3940      "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3941      Matcher));
3942  EXPECT_TRUE(matches(
3943      "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3944      Matcher));
3945}
3946
3947TEST(IsExplicitTemplateSpecialization,
3948     DoesNotMatchPrimaryTemplate) {
3949  EXPECT_TRUE(notMatches(
3950      "template <typename T> class X {};",
3951      cxxRecordDecl(isExplicitTemplateSpecialization())));
3952  EXPECT_TRUE(notMatches(
3953      "template <typename T> void f(T t);",
3954      functionDecl(isExplicitTemplateSpecialization())));
3955}
3956
3957TEST(IsExplicitTemplateSpecialization,
3958     DoesNotMatchExplicitTemplateInstantiations) {
3959  EXPECT_TRUE(notMatches(
3960      "template <typename T> class X {};"
3961      "template class X<int>; extern template class X<long>;",
3962      cxxRecordDecl(isExplicitTemplateSpecialization())));
3963  EXPECT_TRUE(notMatches(
3964      "template <typename T> void f(T t) {}"
3965      "template void f(int t); extern template void f(long t);",
3966      functionDecl(isExplicitTemplateSpecialization())));
3967}
3968
3969TEST(IsExplicitTemplateSpecialization,
3970     DoesNotMatchImplicitTemplateInstantiations) {
3971  EXPECT_TRUE(notMatches(
3972      "template <typename T> class X {}; X<int> x;",
3973      cxxRecordDecl(isExplicitTemplateSpecialization())));
3974  EXPECT_TRUE(notMatches(
3975      "template <typename T> void f(T t); void g() { f(10); }",
3976      functionDecl(isExplicitTemplateSpecialization())));
3977}
3978
3979TEST(IsExplicitTemplateSpecialization,
3980     MatchesExplicitTemplateSpecializations) {
3981  EXPECT_TRUE(matches(
3982      "template <typename T> class X {};"
3983      "template<> class X<int> {};",
3984      cxxRecordDecl(isExplicitTemplateSpecialization())));
3985  EXPECT_TRUE(matches(
3986      "template <typename T> void f(T t) {}"
3987      "template<> void f(int t) {}",
3988      functionDecl(isExplicitTemplateSpecialization())));
3989}
3990
3991TEST(HasAncenstor, MatchesDeclarationAncestors) {
3992  EXPECT_TRUE(matches(
3993      "class A { class B { class C {}; }; };",
3994      recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3995}
3996
3997TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3998  EXPECT_TRUE(notMatches(
3999      "class A { class B { class C {}; }; };",
4000      recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
4001}
4002
4003TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
4004  EXPECT_TRUE(matches(
4005      "class A { class B { void f() { C c; } class C {}; }; };",
4006      varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
4007          hasAncestor(recordDecl(hasName("A"))))))));
4008}
4009
4010TEST(HasAncenstor, MatchesStatementAncestors) {
4011  EXPECT_TRUE(matches(
4012      "void f() { if (true) { while (false) { 42; } } }",
4013      integerLiteral(equals(42), hasAncestor(ifStmt()))));
4014}
4015
4016TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
4017  EXPECT_TRUE(matches(
4018      "void f() { if (true) { int x = 42; } }",
4019      integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
4020}
4021
4022TEST(HasAncestor, BindsRecursiveCombinations) {
4023  EXPECT_TRUE(matchAndVerifyResultTrue(
4024      "class C { class D { class E { class F { int y; }; }; }; };",
4025      fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
4026      new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
4027}
4028
4029TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
4030  EXPECT_TRUE(matchAndVerifyResultTrue(
4031      "class C { class D { class E { class F { int y; }; }; }; };",
4032      fieldDecl(hasAncestor(
4033          decl(
4034            hasDescendant(recordDecl(isDefinition(),
4035                                     hasAncestor(recordDecl())))
4036          ).bind("d")
4037      )),
4038      new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
4039}
4040
4041TEST(HasAncestor, MatchesClosestAncestor) {
4042  EXPECT_TRUE(matchAndVerifyResultTrue(
4043      "template <typename T> struct C {"
4044      "  void f(int) {"
4045      "    struct I { void g(T) { int x; } } i; i.g(42);"
4046      "  }"
4047      "};"
4048      "template struct C<int>;",
4049      varDecl(hasName("x"),
4050              hasAncestor(functionDecl(hasParameter(
4051                  0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
4052      new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
4053}
4054
4055TEST(HasAncestor, MatchesInTemplateInstantiations) {
4056  EXPECT_TRUE(matches(
4057      "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
4058      "A<int>::B::C a;",
4059      fieldDecl(hasType(asString("int")),
4060                hasAncestor(recordDecl(hasName("A"))))));
4061}
4062
4063TEST(HasAncestor, MatchesInImplicitCode) {
4064  EXPECT_TRUE(matches(
4065      "struct X {}; struct A { A() {} X x; };",
4066      cxxConstructorDecl(
4067          hasAnyConstructorInitializer(withInitializer(expr(
4068              hasAncestor(recordDecl(hasName("A")))))))));
4069}
4070
4071TEST(HasParent, MatchesOnlyParent) {
4072  EXPECT_TRUE(matches(
4073      "void f() { if (true) { int x = 42; } }",
4074      compoundStmt(hasParent(ifStmt()))));
4075  EXPECT_TRUE(notMatches(
4076      "void f() { for (;;) { int x = 42; } }",
4077      compoundStmt(hasParent(ifStmt()))));
4078  EXPECT_TRUE(notMatches(
4079      "void f() { if (true) for (;;) { int x = 42; } }",
4080      compoundStmt(hasParent(ifStmt()))));
4081}
4082
4083TEST(HasAncestor, MatchesAllAncestors) {
4084  EXPECT_TRUE(matches(
4085      "template <typename T> struct C { static void f() { 42; } };"
4086      "void t() { C<int>::f(); }",
4087      integerLiteral(
4088          equals(42),
4089          allOf(
4090              hasAncestor(cxxRecordDecl(isTemplateInstantiation())),
4091              hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation())))))));
4092}
4093
4094TEST(HasParent, MatchesAllParents) {
4095  EXPECT_TRUE(matches(
4096      "template <typename T> struct C { static void f() { 42; } };"
4097      "void t() { C<int>::f(); }",
4098      integerLiteral(
4099          equals(42),
4100          hasParent(compoundStmt(hasParent(functionDecl(
4101              hasParent(cxxRecordDecl(isTemplateInstantiation())))))))));
4102  EXPECT_TRUE(
4103      matches("template <typename T> struct C { static void f() { 42; } };"
4104              "void t() { C<int>::f(); }",
4105              integerLiteral(
4106                  equals(42),
4107                  hasParent(compoundStmt(hasParent(functionDecl(hasParent(
4108                      cxxRecordDecl(unless(isTemplateInstantiation()))))))))));
4109  EXPECT_TRUE(matches(
4110      "template <typename T> struct C { static void f() { 42; } };"
4111      "void t() { C<int>::f(); }",
4112      integerLiteral(equals(42),
4113                     hasParent(compoundStmt(
4114                         allOf(hasParent(functionDecl(hasParent(
4115                                   cxxRecordDecl(isTemplateInstantiation())))),
4116                               hasParent(functionDecl(hasParent(cxxRecordDecl(
4117                                   unless(isTemplateInstantiation())))))))))));
4118  EXPECT_TRUE(
4119      notMatches("template <typename T> struct C { static void f() {} };"
4120                 "void t() { C<int>::f(); }",
4121                 compoundStmt(hasParent(recordDecl()))));
4122}
4123
4124TEST(HasParent, NoDuplicateParents) {
4125  class HasDuplicateParents : public BoundNodesCallback {
4126  public:
4127    bool run(const BoundNodes *Nodes) override { return false; }
4128    bool run(const BoundNodes *Nodes, ASTContext *Context) override {
4129      const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
4130      std::set<const void *> Parents;
4131      for (const auto &Parent : Context->getParents(*Node)) {
4132        if (!Parents.insert(Parent.getMemoizationData()).second) {
4133          return true;
4134        }
4135      }
4136      return false;
4137    }
4138  };
4139  EXPECT_FALSE(matchAndVerifyResultTrue(
4140      "template <typename T> int Foo() { return 1 + 2; }\n"
4141      "int x = Foo<int>() + Foo<unsigned>();",
4142      stmt().bind("node"), new HasDuplicateParents()));
4143}
4144
4145TEST(TypeMatching, MatchesTypes) {
4146  EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
4147}
4148
4149TEST(TypeMatching, MatchesVoid) {
4150  EXPECT_TRUE(matches("struct S { void func(); };",
4151                      cxxMethodDecl(returns(voidType()))));
4152}
4153
4154TEST(TypeMatching, MatchesArrayTypes) {
4155  EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
4156  EXPECT_TRUE(matches("int a[42];", arrayType()));
4157  EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
4158
4159  EXPECT_TRUE(notMatches("struct A {}; A a[7];",
4160                         arrayType(hasElementType(builtinType()))));
4161
4162  EXPECT_TRUE(matches(
4163      "int const a[] = { 2, 3 };",
4164      qualType(arrayType(hasElementType(builtinType())))));
4165  EXPECT_TRUE(matches(
4166      "int const a[] = { 2, 3 };",
4167      qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4168  EXPECT_TRUE(matches(
4169      "typedef const int T; T x[] = { 1, 2 };",
4170      qualType(isConstQualified(), arrayType())));
4171
4172  EXPECT_TRUE(notMatches(
4173      "int a[] = { 2, 3 };",
4174      qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4175  EXPECT_TRUE(notMatches(
4176      "int a[] = { 2, 3 };",
4177      qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
4178  EXPECT_TRUE(notMatches(
4179      "int const a[] = { 2, 3 };",
4180      qualType(arrayType(hasElementType(builtinType())),
4181               unless(isConstQualified()))));
4182
4183  EXPECT_TRUE(matches("int a[2];",
4184                      constantArrayType(hasElementType(builtinType()))));
4185  EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
4186}
4187
4188TEST(TypeMatching, DecayedType) {
4189  EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
4190  EXPECT_TRUE(notMatches("int i[7];", decayedType()));
4191}
4192
4193TEST(TypeMatching, MatchesComplexTypes) {
4194  EXPECT_TRUE(matches("_Complex float f;", complexType()));
4195  EXPECT_TRUE(matches(
4196    "_Complex float f;",
4197    complexType(hasElementType(builtinType()))));
4198  EXPECT_TRUE(notMatches(
4199    "_Complex float f;",
4200    complexType(hasElementType(isInteger()))));
4201}
4202
4203TEST(TypeMatching, MatchesConstantArrayTypes) {
4204  EXPECT_TRUE(matches("int a[2];", constantArrayType()));
4205  EXPECT_TRUE(notMatches(
4206    "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
4207    constantArrayType(hasElementType(builtinType()))));
4208
4209  EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
4210  EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
4211  EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
4212}
4213
4214TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
4215  EXPECT_TRUE(matches(
4216    "template <typename T, int Size> class array { T data[Size]; };",
4217    dependentSizedArrayType()));
4218  EXPECT_TRUE(notMatches(
4219    "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
4220    dependentSizedArrayType()));
4221}
4222
4223TEST(TypeMatching, MatchesIncompleteArrayType) {
4224  EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
4225  EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
4226
4227  EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
4228                         incompleteArrayType()));
4229}
4230
4231TEST(TypeMatching, MatchesVariableArrayType) {
4232  EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
4233  EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4234
4235  EXPECT_TRUE(matches(
4236    "void f(int b) { int a[b]; }",
4237    variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4238      varDecl(hasName("b")))))))));
4239}
4240
4241TEST(TypeMatching, MatchesAtomicTypes) {
4242  if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4243      llvm::Triple::Win32) {
4244    // FIXME: Make this work for MSVC.
4245    EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
4246
4247    EXPECT_TRUE(matches("_Atomic(int) i;",
4248                        atomicType(hasValueType(isInteger()))));
4249    EXPECT_TRUE(notMatches("_Atomic(float) f;",
4250                           atomicType(hasValueType(isInteger()))));
4251  }
4252}
4253
4254TEST(TypeMatching, MatchesAutoTypes) {
4255  EXPECT_TRUE(matches("auto i = 2;", autoType()));
4256  EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4257                      autoType()));
4258
4259  // FIXME: Matching against the type-as-written can't work here, because the
4260  //        type as written was not deduced.
4261  //EXPECT_TRUE(matches("auto a = 1;",
4262  //                    autoType(hasDeducedType(isInteger()))));
4263  //EXPECT_TRUE(notMatches("auto b = 2.0;",
4264  //                       autoType(hasDeducedType(isInteger()))));
4265}
4266
4267TEST(TypeMatching, MatchesFunctionTypes) {
4268  EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4269  EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4270}
4271
4272TEST(TypeMatching, MatchesParenType) {
4273  EXPECT_TRUE(
4274      matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4275  EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4276
4277  EXPECT_TRUE(matches(
4278      "int (*ptr_to_func)(int);",
4279      varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4280  EXPECT_TRUE(notMatches(
4281      "int (*ptr_to_array)[4];",
4282      varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4283}
4284
4285TEST(TypeMatching, PointerTypes) {
4286  // FIXME: Reactive when these tests can be more specific (not matching
4287  // implicit code on certain platforms), likely when we have hasDescendant for
4288  // Types/TypeLocs.
4289  //EXPECT_TRUE(matchAndVerifyResultTrue(
4290  //    "int* a;",
4291  //    pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4292  //    new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4293  //EXPECT_TRUE(matchAndVerifyResultTrue(
4294  //    "int* a;",
4295  //    pointerTypeLoc().bind("loc"),
4296  //    new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4297  EXPECT_TRUE(matches(
4298      "int** a;",
4299      loc(pointerType(pointee(qualType())))));
4300  EXPECT_TRUE(matches(
4301      "int** a;",
4302      loc(pointerType(pointee(pointerType())))));
4303  EXPECT_TRUE(matches(
4304      "int* b; int* * const a = &b;",
4305      loc(qualType(isConstQualified(), pointerType()))));
4306
4307  std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
4308  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4309                                           hasType(blockPointerType()))));
4310  EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4311                                        hasType(memberPointerType()))));
4312  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4313                                           hasType(pointerType()))));
4314  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4315                                           hasType(referenceType()))));
4316  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4317                                           hasType(lValueReferenceType()))));
4318  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4319                                           hasType(rValueReferenceType()))));
4320
4321  Fragment = "int *ptr;";
4322  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4323                                           hasType(blockPointerType()))));
4324  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4325                                           hasType(memberPointerType()))));
4326  EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4327                                        hasType(pointerType()))));
4328  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4329                                           hasType(referenceType()))));
4330
4331  Fragment = "int a; int &ref = a;";
4332  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4333                                           hasType(blockPointerType()))));
4334  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4335                                           hasType(memberPointerType()))));
4336  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4337                                           hasType(pointerType()))));
4338  EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4339                                        hasType(referenceType()))));
4340  EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4341                                        hasType(lValueReferenceType()))));
4342  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4343                                           hasType(rValueReferenceType()))));
4344
4345  Fragment = "int &&ref = 2;";
4346  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4347                                           hasType(blockPointerType()))));
4348  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4349                                           hasType(memberPointerType()))));
4350  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4351                                           hasType(pointerType()))));
4352  EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4353                                        hasType(referenceType()))));
4354  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4355                                           hasType(lValueReferenceType()))));
4356  EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4357                                        hasType(rValueReferenceType()))));
4358}
4359
4360TEST(TypeMatching, AutoRefTypes) {
4361  std::string Fragment = "auto a = 1;"
4362                         "auto b = a;"
4363                         "auto &c = a;"
4364                         "auto &&d = c;"
4365                         "auto &&e = 2;";
4366  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4367                                           hasType(referenceType()))));
4368  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4369                                           hasType(referenceType()))));
4370  EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4371                                        hasType(referenceType()))));
4372  EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4373                                        hasType(lValueReferenceType()))));
4374  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4375                                           hasType(rValueReferenceType()))));
4376  EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4377                                        hasType(referenceType()))));
4378  EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4379                                        hasType(lValueReferenceType()))));
4380  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4381                                           hasType(rValueReferenceType()))));
4382  EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4383                                        hasType(referenceType()))));
4384  EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4385                                           hasType(lValueReferenceType()))));
4386  EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4387                                        hasType(rValueReferenceType()))));
4388}
4389
4390TEST(TypeMatching, PointeeTypes) {
4391  EXPECT_TRUE(matches("int b; int &a = b;",
4392                      referenceType(pointee(builtinType()))));
4393  EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4394
4395  EXPECT_TRUE(matches("int *a;",
4396                      loc(pointerType(pointee(builtinType())))));
4397
4398  EXPECT_TRUE(matches(
4399      "int const *A;",
4400      pointerType(pointee(isConstQualified(), builtinType()))));
4401  EXPECT_TRUE(notMatches(
4402      "int *A;",
4403      pointerType(pointee(isConstQualified(), builtinType()))));
4404}
4405
4406TEST(TypeMatching, MatchesPointersToConstTypes) {
4407  EXPECT_TRUE(matches("int b; int * const a = &b;",
4408                      loc(pointerType())));
4409  EXPECT_TRUE(matches("int b; int * const a = &b;",
4410                      loc(pointerType())));
4411  EXPECT_TRUE(matches(
4412      "int b; const int * a = &b;",
4413      loc(pointerType(pointee(builtinType())))));
4414  EXPECT_TRUE(matches(
4415      "int b; const int * a = &b;",
4416      pointerType(pointee(builtinType()))));
4417}
4418
4419TEST(TypeMatching, MatchesTypedefTypes) {
4420  EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4421                                                     hasType(typedefType()))));
4422}
4423
4424TEST(TypeMatching, MatchesTemplateSpecializationType) {
4425  EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
4426                      templateSpecializationType()));
4427}
4428
4429TEST(TypeMatching, MatchesRecordType) {
4430  EXPECT_TRUE(matches("class C{}; C c;", recordType()));
4431  EXPECT_TRUE(matches("struct S{}; S s;",
4432                      recordType(hasDeclaration(recordDecl(hasName("S"))))));
4433  EXPECT_TRUE(notMatches("int i;",
4434                         recordType(hasDeclaration(recordDecl(hasName("S"))))));
4435}
4436
4437TEST(TypeMatching, MatchesElaboratedType) {
4438  EXPECT_TRUE(matches(
4439    "namespace N {"
4440    "  namespace M {"
4441    "    class D {};"
4442    "  }"
4443    "}"
4444    "N::M::D d;", elaboratedType()));
4445  EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4446  EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4447}
4448
4449TEST(ElaboratedTypeNarrowing, hasQualifier) {
4450  EXPECT_TRUE(matches(
4451    "namespace N {"
4452    "  namespace M {"
4453    "    class D {};"
4454    "  }"
4455    "}"
4456    "N::M::D d;",
4457    elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4458  EXPECT_TRUE(notMatches(
4459    "namespace M {"
4460    "  class D {};"
4461    "}"
4462    "M::D d;",
4463    elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4464  EXPECT_TRUE(notMatches(
4465    "struct D {"
4466    "} d;",
4467    elaboratedType(hasQualifier(nestedNameSpecifier()))));
4468}
4469
4470TEST(ElaboratedTypeNarrowing, namesType) {
4471  EXPECT_TRUE(matches(
4472    "namespace N {"
4473    "  namespace M {"
4474    "    class D {};"
4475    "  }"
4476    "}"
4477    "N::M::D d;",
4478    elaboratedType(elaboratedType(namesType(recordType(
4479        hasDeclaration(namedDecl(hasName("D")))))))));
4480  EXPECT_TRUE(notMatches(
4481    "namespace M {"
4482    "  class D {};"
4483    "}"
4484    "M::D d;",
4485    elaboratedType(elaboratedType(namesType(typedefType())))));
4486}
4487
4488TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
4489  const std::string code = "template <typename T>"
4490                           "int F() {"
4491                           "  return 1 + T();"
4492                           "}"
4493                           "int i = F<int>();";
4494  EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
4495                                 expr(hasType(substTemplateTypeParmType()))))));
4496  EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
4497                                expr(hasType(substTemplateTypeParmType()))))));
4498}
4499
4500TEST(NNS, MatchesNestedNameSpecifiers) {
4501  EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4502                      nestedNameSpecifier()));
4503  EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4504                      nestedNameSpecifier()));
4505  EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4506                      nestedNameSpecifier()));
4507  EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
4508                      nestedNameSpecifier()));
4509
4510  EXPECT_TRUE(matches(
4511    "struct A { static void f() {} }; void g() { A::f(); }",
4512    nestedNameSpecifier()));
4513  EXPECT_TRUE(notMatches(
4514    "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4515    nestedNameSpecifier()));
4516}
4517
4518TEST(NullStatement, SimpleCases) {
4519  EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4520  EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4521}
4522
4523TEST(NS, Anonymous) {
4524  EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
4525  EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
4526}
4527
4528TEST(NS, Alias) {
4529  EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
4530                      namespaceAliasDecl(hasName("alias"))));
4531}
4532
4533TEST(NNS, MatchesTypes) {
4534  NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4535    specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4536  EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4537  EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4538                      Matcher));
4539  EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4540}
4541
4542TEST(NNS, MatchesNamespaceDecls) {
4543  NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4544    specifiesNamespace(hasName("ns")));
4545  EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4546  EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4547  EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4548}
4549
4550TEST(NNS, BindsNestedNameSpecifiers) {
4551  EXPECT_TRUE(matchAndVerifyResultTrue(
4552      "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4553      nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4554      new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4555}
4556
4557TEST(NNS, BindsNestedNameSpecifierLocs) {
4558  EXPECT_TRUE(matchAndVerifyResultTrue(
4559      "namespace ns { struct B {}; } ns::B b;",
4560      loc(nestedNameSpecifier()).bind("loc"),
4561      new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4562}
4563
4564TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4565  EXPECT_TRUE(matches(
4566      "struct A { struct B { struct C {}; }; }; A::B::C c;",
4567      nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4568  EXPECT_TRUE(matches(
4569      "struct A { struct B { struct C {}; }; }; A::B::C c;",
4570      nestedNameSpecifierLoc(hasPrefix(
4571          specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
4572}
4573
4574TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4575  std::string Fragment =
4576      "namespace a { struct A { struct B { struct C {}; }; }; };"
4577      "void f() { a::A::B::C c; }";
4578  EXPECT_TRUE(matches(
4579      Fragment,
4580      nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4581                          hasDescendant(nestedNameSpecifier(
4582                              specifiesNamespace(hasName("a")))))));
4583  EXPECT_TRUE(notMatches(
4584      Fragment,
4585      nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4586                          has(nestedNameSpecifier(
4587                              specifiesNamespace(hasName("a")))))));
4588  EXPECT_TRUE(matches(
4589      Fragment,
4590      nestedNameSpecifier(specifiesType(asString("struct a::A")),
4591                          has(nestedNameSpecifier(
4592                              specifiesNamespace(hasName("a")))))));
4593
4594  // Not really useful because a NestedNameSpecifier can af at most one child,
4595  // but to complete the interface.
4596  EXPECT_TRUE(matchAndVerifyResultTrue(
4597      Fragment,
4598      nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4599                          forEach(nestedNameSpecifier().bind("x"))),
4600      new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4601}
4602
4603TEST(NNS, NestedNameSpecifiersAsDescendants) {
4604  std::string Fragment =
4605      "namespace a { struct A { struct B { struct C {}; }; }; };"
4606      "void f() { a::A::B::C c; }";
4607  EXPECT_TRUE(matches(
4608      Fragment,
4609      decl(hasDescendant(nestedNameSpecifier(specifiesType(
4610          asString("struct a::A")))))));
4611  EXPECT_TRUE(matchAndVerifyResultTrue(
4612      Fragment,
4613      functionDecl(hasName("f"),
4614                   forEachDescendant(nestedNameSpecifier().bind("x"))),
4615      // Nested names: a, a::A and a::A::B.
4616      new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4617}
4618
4619TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4620  std::string Fragment =
4621      "namespace a { struct A { struct B { struct C {}; }; }; };"
4622      "void f() { a::A::B::C c; }";
4623  EXPECT_TRUE(matches(
4624      Fragment,
4625      nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4626                             hasDescendant(loc(nestedNameSpecifier(
4627                                 specifiesNamespace(hasName("a"))))))));
4628  EXPECT_TRUE(notMatches(
4629      Fragment,
4630      nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4631                             has(loc(nestedNameSpecifier(
4632                                 specifiesNamespace(hasName("a"))))))));
4633  EXPECT_TRUE(matches(
4634      Fragment,
4635      nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4636                             has(loc(nestedNameSpecifier(
4637                                 specifiesNamespace(hasName("a"))))))));
4638
4639  EXPECT_TRUE(matchAndVerifyResultTrue(
4640      Fragment,
4641      nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4642                             forEach(nestedNameSpecifierLoc().bind("x"))),
4643      new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4644}
4645
4646TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4647  std::string Fragment =
4648      "namespace a { struct A { struct B { struct C {}; }; }; };"
4649      "void f() { a::A::B::C c; }";
4650  EXPECT_TRUE(matches(
4651      Fragment,
4652      decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4653          asString("struct a::A"))))))));
4654  EXPECT_TRUE(matchAndVerifyResultTrue(
4655      Fragment,
4656      functionDecl(hasName("f"),
4657                   forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4658      // Nested names: a, a::A and a::A::B.
4659      new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4660}
4661
4662template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
4663public:
4664  VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4665                    StringRef InnerId)
4666      : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
4667  }
4668
4669  bool run(const BoundNodes *Nodes) override { return false; }
4670
4671  bool run(const BoundNodes *Nodes, ASTContext *Context) override {
4672    const T *Node = Nodes->getNodeAs<T>(Id);
4673    return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4674           nullptr;
4675  }
4676private:
4677  std::string Id;
4678  internal::Matcher<T> InnerMatcher;
4679  std::string InnerId;
4680};
4681
4682TEST(MatchFinder, CanMatchDeclarationsRecursively) {
4683  EXPECT_TRUE(matchAndVerifyResultTrue(
4684      "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4685      new VerifyMatchOnNode<clang::Decl>(
4686          "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4687          "Y")));
4688  EXPECT_TRUE(matchAndVerifyResultFalse(
4689      "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4690      new VerifyMatchOnNode<clang::Decl>(
4691          "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4692          "Z")));
4693}
4694
4695TEST(MatchFinder, CanMatchStatementsRecursively) {
4696  EXPECT_TRUE(matchAndVerifyResultTrue(
4697      "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
4698      new VerifyMatchOnNode<clang::Stmt>(
4699          "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
4700  EXPECT_TRUE(matchAndVerifyResultFalse(
4701      "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
4702      new VerifyMatchOnNode<clang::Stmt>(
4703          "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
4704}
4705
4706TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4707  EXPECT_TRUE(matchAndVerifyResultTrue(
4708      "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4709      new VerifyMatchOnNode<clang::Decl>(
4710          "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
4711  EXPECT_TRUE(matchAndVerifyResultFalse(
4712      "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4713      new VerifyMatchOnNode<clang::Decl>(
4714          "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
4715}
4716
4717template <typename T>
4718class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4719public:
4720  bool run(const BoundNodes *Nodes) override { return false; }
4721
4722  bool run(const BoundNodes *Nodes, ASTContext *Context) override {
4723    const T *Node = Nodes->getNodeAs<T>("");
4724    return verify(*Nodes, *Context, Node);
4725  }
4726
4727  bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
4728    // Use the original typed pointer to verify we can pass pointers to subtypes
4729    // to equalsNode.
4730    const T *TypedNode = cast<T>(Node);
4731    return selectFirst<T>(
4732               "", match(stmt(hasParent(
4733                             stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
4734                         *Node, Context)) != nullptr;
4735  }
4736  bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
4737    // Use the original typed pointer to verify we can pass pointers to subtypes
4738    // to equalsNode.
4739    const T *TypedNode = cast<T>(Node);
4740    return selectFirst<T>(
4741               "", match(decl(hasParent(
4742                             decl(has(decl(equalsNode(TypedNode)))).bind(""))),
4743                         *Node, Context)) != nullptr;
4744  }
4745  bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
4746    // Use the original typed pointer to verify we can pass pointers to subtypes
4747    // to equalsNode.
4748    const T *TypedNode = cast<T>(Node);
4749    const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
4750    return selectFirst<T>(
4751               "", match(fieldDecl(hasParent(decl(has(fieldDecl(
4752                             hasType(type(equalsNode(TypedNode)).bind(""))))))),
4753                         *Dec, Context)) != nullptr;
4754  }
4755};
4756
4757TEST(IsEqualTo, MatchesNodesByIdentity) {
4758  EXPECT_TRUE(matchAndVerifyResultTrue(
4759      "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
4760      new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4761  EXPECT_TRUE(matchAndVerifyResultTrue(
4762      "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4763      new VerifyAncestorHasChildIsEqual<IfStmt>()));
4764  EXPECT_TRUE(matchAndVerifyResultTrue(
4765      "class X { class Y {} y; };",
4766      fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
4767      new VerifyAncestorHasChildIsEqual<Type>()));
4768}
4769
4770TEST(MatchFinder, CheckProfiling) {
4771  MatchFinder::MatchFinderOptions Options;
4772  llvm::StringMap<llvm::TimeRecord> Records;
4773  Options.CheckProfiling.emplace(Records);
4774  MatchFinder Finder(std::move(Options));
4775
4776  struct NamedCallback : public MatchFinder::MatchCallback {
4777    void run(const MatchFinder::MatchResult &Result) override {}
4778    StringRef getID() const override { return "MyID"; }
4779  } Callback;
4780  Finder.addMatcher(decl(), &Callback);
4781  std::unique_ptr<FrontendActionFactory> Factory(
4782      newFrontendActionFactory(&Finder));
4783  ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4784
4785  EXPECT_EQ(1u, Records.size());
4786  EXPECT_EQ("MyID", Records.begin()->getKey());
4787}
4788
4789class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4790public:
4791  VerifyStartOfTranslationUnit() : Called(false) {}
4792  void run(const MatchFinder::MatchResult &Result) override {
4793    EXPECT_TRUE(Called);
4794  }
4795  void onStartOfTranslationUnit() override { Called = true; }
4796  bool Called;
4797};
4798
4799TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4800  MatchFinder Finder;
4801  VerifyStartOfTranslationUnit VerifyCallback;
4802  Finder.addMatcher(decl(), &VerifyCallback);
4803  std::unique_ptr<FrontendActionFactory> Factory(
4804      newFrontendActionFactory(&Finder));
4805  ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4806  EXPECT_TRUE(VerifyCallback.Called);
4807
4808  VerifyCallback.Called = false;
4809  std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
4810  ASSERT_TRUE(AST.get());
4811  Finder.matchAST(AST->getASTContext());
4812  EXPECT_TRUE(VerifyCallback.Called);
4813}
4814
4815class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4816public:
4817  VerifyEndOfTranslationUnit() : Called(false) {}
4818  void run(const MatchFinder::MatchResult &Result) override {
4819    EXPECT_FALSE(Called);
4820  }
4821  void onEndOfTranslationUnit() override { Called = true; }
4822  bool Called;
4823};
4824
4825TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4826  MatchFinder Finder;
4827  VerifyEndOfTranslationUnit VerifyCallback;
4828  Finder.addMatcher(decl(), &VerifyCallback);
4829  std::unique_ptr<FrontendActionFactory> Factory(
4830      newFrontendActionFactory(&Finder));
4831  ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4832  EXPECT_TRUE(VerifyCallback.Called);
4833
4834  VerifyCallback.Called = false;
4835  std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
4836  ASSERT_TRUE(AST.get());
4837  Finder.matchAST(AST->getASTContext());
4838  EXPECT_TRUE(VerifyCallback.Called);
4839}
4840
4841TEST(EqualsBoundNodeMatcher, QualType) {
4842  EXPECT_TRUE(matches(
4843      "int i = 1;", varDecl(hasType(qualType().bind("type")),
4844                            hasInitializer(ignoringParenImpCasts(
4845                                hasType(qualType(equalsBoundNode("type"))))))));
4846  EXPECT_TRUE(notMatches("int i = 1.f;",
4847                         varDecl(hasType(qualType().bind("type")),
4848                                 hasInitializer(ignoringParenImpCasts(hasType(
4849                                     qualType(equalsBoundNode("type"))))))));
4850}
4851
4852TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4853  EXPECT_TRUE(notMatches(
4854      "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4855                            hasInitializer(ignoringParenImpCasts(
4856                                hasType(qualType(equalsBoundNode("type"))))))));
4857}
4858
4859TEST(EqualsBoundNodeMatcher, Stmt) {
4860  EXPECT_TRUE(
4861      matches("void f() { if(true) {} }",
4862              stmt(allOf(ifStmt().bind("if"),
4863                         hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4864
4865  EXPECT_TRUE(notMatches(
4866      "void f() { if(true) { if (true) {} } }",
4867      stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4868}
4869
4870TEST(EqualsBoundNodeMatcher, Decl) {
4871  EXPECT_TRUE(matches(
4872      "class X { class Y {}; };",
4873      decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4874                 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4875
4876  EXPECT_TRUE(notMatches("class X { class Y {}; };",
4877                         decl(allOf(recordDecl(hasName("::X")).bind("record"),
4878                                    has(decl(equalsBoundNode("record")))))));
4879}
4880
4881TEST(EqualsBoundNodeMatcher, Type) {
4882  EXPECT_TRUE(matches(
4883      "class X { int a; int b; };",
4884      recordDecl(
4885          has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4886          has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4887
4888  EXPECT_TRUE(notMatches(
4889      "class X { int a; double b; };",
4890      recordDecl(
4891          has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4892          has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4893}
4894
4895TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
4896  EXPECT_TRUE(matchAndVerifyResultTrue(
4897      "int f() {"
4898      "  if (1) {"
4899      "    int i = 9;"
4900      "  }"
4901      "  int j = 10;"
4902      "  {"
4903      "    float k = 9.0;"
4904      "  }"
4905      "  return 0;"
4906      "}",
4907      // Look for variable declarations within functions whose type is the same
4908      // as the function return type.
4909      functionDecl(returns(qualType().bind("type")),
4910                   forEachDescendant(varDecl(hasType(
4911                       qualType(equalsBoundNode("type")))).bind("decl"))),
4912      // Only i and j should match, not k.
4913      new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4914}
4915
4916TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4917  EXPECT_TRUE(matchAndVerifyResultTrue(
4918      "void f() {"
4919      "  int x;"
4920      "  double d;"
4921      "  x = d + x - d + x;"
4922      "}",
4923      functionDecl(
4924          hasName("f"), forEachDescendant(varDecl().bind("d")),
4925          forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4926      new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4927}
4928
4929TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4930  EXPECT_TRUE(matchAndVerifyResultTrue(
4931      "struct StringRef { int size() const; const char* data() const; };"
4932      "void f(StringRef v) {"
4933      "  v.data();"
4934      "}",
4935      cxxMemberCallExpr(
4936          callee(cxxMethodDecl(hasName("data"))),
4937          on(declRefExpr(to(
4938              varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
4939          unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
4940              callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
4941              on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4942          .bind("data"),
4943      new VerifyIdIsBoundTo<Expr>("data", 1)));
4944
4945  EXPECT_FALSE(matches(
4946      "struct StringRef { int size() const; const char* data() const; };"
4947      "void f(StringRef v) {"
4948      "  v.data();"
4949      "  v.size();"
4950      "}",
4951      cxxMemberCallExpr(
4952          callee(cxxMethodDecl(hasName("data"))),
4953          on(declRefExpr(to(
4954              varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
4955          unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
4956              callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
4957              on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4958          .bind("data")));
4959}
4960
4961TEST(TypeDefDeclMatcher, Match) {
4962  EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4963                      typedefDecl(hasName("typedefDeclTest"))));
4964}
4965
4966TEST(IsInlineMatcher, IsInline) {
4967  EXPECT_TRUE(matches("void g(); inline void f();",
4968                      functionDecl(isInline(), hasName("f"))));
4969  EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
4970                      namespaceDecl(isInline(), hasName("m"))));
4971}
4972
4973// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4974#ifndef LLVM_ON_WIN32
4975
4976TEST(Matcher, IsExpansionInMainFileMatcher) {
4977  EXPECT_TRUE(matches("class X {};",
4978                      recordDecl(hasName("X"), isExpansionInMainFile())));
4979  EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4980  FileContentMappings M;
4981  M.push_back(std::make_pair("/other", "class X {};"));
4982  EXPECT_TRUE(matchesConditionally("#include <other>\n",
4983                                   recordDecl(isExpansionInMainFile()), false,
4984                                   "-isystem/", M));
4985}
4986
4987TEST(Matcher, IsExpansionInSystemHeader) {
4988  FileContentMappings M;
4989  M.push_back(std::make_pair("/other", "class X {};"));
4990  EXPECT_TRUE(matchesConditionally(
4991      "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4992      "-isystem/", M));
4993  EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4994                                   recordDecl(isExpansionInSystemHeader()),
4995                                   false, "-I/", M));
4996  EXPECT_TRUE(notMatches("class X {};",
4997                         recordDecl(isExpansionInSystemHeader())));
4998  EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4999}
5000
5001TEST(Matcher, IsExpansionInFileMatching) {
5002  FileContentMappings M;
5003  M.push_back(std::make_pair("/foo", "class A {};"));
5004  M.push_back(std::make_pair("/bar", "class B {};"));
5005  EXPECT_TRUE(matchesConditionally(
5006      "#include <foo>\n"
5007      "#include <bar>\n"
5008      "class X {};",
5009      recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
5010      "-isystem/", M));
5011  EXPECT_TRUE(matchesConditionally(
5012      "#include <foo>\n"
5013      "#include <bar>\n"
5014      "class X {};",
5015      recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
5016      "-isystem/", M));
5017}
5018
5019#endif // LLVM_ON_WIN32
5020
5021
5022TEST(ObjCMessageExprMatcher, SimpleExprs) {
5023  // don't find ObjCMessageExpr where none are present
5024  EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
5025
5026  std::string Objc1String =
5027  "@interface Str "
5028  " - (Str *)uppercaseString:(Str *)str;"
5029  "@end "
5030  "@interface foo "
5031  "- (void)meth:(Str *)text;"
5032  "@end "
5033  " "
5034  "@implementation foo "
5035  "- (void) meth:(Str *)text { "
5036  "  [self contents];"
5037  "  Str *up = [text uppercaseString];"
5038  "} "
5039  "@end ";
5040  EXPECT_TRUE(matchesObjC(
5041      Objc1String,
5042      objcMessageExpr(anything())));
5043  EXPECT_TRUE(matchesObjC(
5044      Objc1String,
5045      objcMessageExpr(hasSelector("contents"))));
5046  EXPECT_TRUE(matchesObjC(
5047      Objc1String,
5048      objcMessageExpr(matchesSelector("cont*"))));
5049  EXPECT_FALSE(matchesObjC(
5050      Objc1String,
5051      objcMessageExpr(matchesSelector("?cont*"))));
5052  EXPECT_TRUE(notMatchesObjC(
5053      Objc1String,
5054      objcMessageExpr(hasSelector("contents"), hasNullSelector())));
5055  EXPECT_TRUE(matchesObjC(
5056      Objc1String,
5057      objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
5058  EXPECT_TRUE(matchesObjC(
5059      Objc1String,
5060      objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
5061  EXPECT_TRUE(matchesObjC(
5062      Objc1String,
5063      objcMessageExpr(matchesSelector("uppercase*"),
5064                      argumentCountIs(0)
5065                      )));
5066
5067}
5068
5069} // end namespace ast_matchers
5070} // end namespace clang
5071