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