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