blob: 476a0be29040123701790aa4288ede059c76594d [file] [log] [blame]
Manuel Klimek04616e42012-07-06 05:48:52 +00001//===- 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"
Benjamin Kramere5015e52012-12-01 17:22:05 +000011#include "clang/AST/PrettyPrinter.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Chandler Carruth320d9662012-12-04 09:45:34 +000013#include "clang/ASTMatchers/ASTMatchers.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000014#include "clang/Tooling/Tooling.h"
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +000015#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000017#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000022#if GTEST_HAS_DEATH_TEST
Manuel Klimek04616e42012-07-06 05:48:52 +000023TEST(HasNameDeathTest, DiesOnEmptyName) {
24 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000025 DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000026 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27 }, "");
28}
29
Daniel Jasper1dad1832012-07-10 20:20:19 +000030TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000032 DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
Daniel Jasper1dad1832012-07-10 20:20:19 +000033 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34 }, "");
35}
36
Manuel Klimek04616e42012-07-06 05:48:52 +000037TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38 ASSERT_DEBUG_DEATH({
Aaron Ballman512fb642015-09-17 13:30:52 +000039 DeclarationMatcher IsDerivedFromEmpty = cxxRecordDecl(isDerivedFrom(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000040 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41 }, "");
42}
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000043#endif
Manuel Klimek04616e42012-07-06 05:48:52 +000044
Peter Collingbourne2b9471302013-11-07 22:30:32 +000045TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46 MatchFinder Finder;
Craig Topper416fa342014-06-08 08:38:12 +000047 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50 nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000051
52 // Do not accept non-toplevel matchers.
Craig Topper416fa342014-06-08 08:38:12 +000053 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54 EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000056}
57
Manuel Klimeke9235692012-07-25 10:02:02 +000058TEST(Decl, MatchesDeclarations) {
59 EXPECT_TRUE(notMatches("", decl(usingDecl())));
60 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
61 decl(usingDecl())));
62}
63
Manuel Klimek04616e42012-07-06 05:48:52 +000064TEST(NameableDeclaration, MatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000065 DeclarationMatcher NamedX = namedDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +000066 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));
Daniel Jasper1dad1832012-07-10 20:20:19 +000072 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
Manuel Klimek04616e42012-07-06 05:48:52 +000073
74 EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
Daniel Jasper1dad1832012-07-10 20:20:19 +000077TEST(NameableDeclaration, REMatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000078 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000079 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
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000089 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000090 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
91 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
92
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000093 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000094 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));
Manuel Klimeke792efd2012-12-10 07:08:53 +000098
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));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000105}
106
Manuel Klimek04616e42012-07-06 05:48:52 +0000107TEST(DeclarationMatcher, MatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000108 DeclarationMatcher ClassMatcher(recordDecl());
Saleem Abdulrasool377066a2014-03-27 22:50:18 +0000109 llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110 if (Triple.getOS() != llvm::Triple::Win32 ||
111 Triple.getEnvironment() != llvm::Triple::MSVC)
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +0000112 EXPECT_FALSE(matches("", ClassMatcher));
113 else
114 // Matches class type_info.
115 EXPECT_TRUE(matches("", ClassMatcher));
Manuel Klimek04616e42012-07-06 05:48:52 +0000116
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000117 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000118 EXPECT_TRUE(matches("class X;", ClassX));
119 EXPECT_TRUE(matches("class X {};", ClassX));
120 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
121 EXPECT_TRUE(notMatches("", ClassX));
122}
123
124TEST(DeclarationMatcher, ClassIsDerived) {
Aaron Ballman512fb642015-09-17 13:30:52 +0000125 DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000126
127 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000128 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
Manuel Klimek04616e42012-07-06 05:48:52 +0000130 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131 EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
Aaron Ballman512fb642015-09-17 13:30:52 +0000133 DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000134
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
Manuel Klimek04616e42012-07-06 05:48:52 +0000141 DeclarationMatcher ZIsDerivedFromX =
Aaron Ballman512fb642015-09-17 13:30:52 +0000142 cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000143 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));
Manuel Klimek5472a522012-12-04 13:40:29 +0000258 EXPECT_TRUE(
259 notMatches("template<int> struct X;"
260 "template<int i> struct X : public X<i-1> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000261 cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
Manuel Klimek5472a522012-12-04 13:40:29 +0000262 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> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000268 cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000269
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,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000284 varDecl(hasName("z_float"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000285 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000286 EXPECT_TRUE(notMatches(
287 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000288 varDecl(hasName("z_float"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000289 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000290 EXPECT_TRUE(matches(
291 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000292 varDecl(hasName("z_char"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000293 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000294 isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000295
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,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000309 varDecl(hasName("z_float"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000310 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000311 EXPECT_TRUE(notMatches(
312 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000313 varDecl(hasName("z_float"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000314 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000315 EXPECT_TRUE(matches(
316 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000317 varDecl(hasName("z_char"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000318 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000319 isDerivedFrom("Base2")))))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Aaron Ballman512fb642015-09-17 13:30:52 +0000322 cxxRecordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000325 cxxRecordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000329 cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
Manuel Klimek1863e502013-08-02 21:24:09 +0000330
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> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000335 cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000336}
337
Edwin Vane0a4836e2013-03-06 17:02:57 +0000338TEST(DeclarationMatcher, hasMethod) {
339 EXPECT_TRUE(matches("class A { void func(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +0000340 cxxRecordDecl(hasMethod(hasName("func")))));
Edwin Vane0a4836e2013-03-06 17:02:57 +0000341 EXPECT_TRUE(notMatches("class A { void func(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +0000342 cxxRecordDecl(hasMethod(isPublic()))));
Edwin Vane0a4836e2013-03-06 17:02:57 +0000343}
344
Daniel Jasper83dafaf2012-09-18 14:17:42 +0000345TEST(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;",
Aaron Ballman512fb642015-09-17 13:30:52 +0000352 cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
Daniel Jasper83dafaf2012-09-18 14:17:42 +0000353}
354
Edwin Vaneb6eae142013-02-25 20:43:32 +0000355TEST(DeclarationMatcher, hasDeclContext) {
356 EXPECT_TRUE(matches(
357 "namespace N {"
358 " namespace M {"
359 " class D {};"
360 " }"
361 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000362 recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000363 EXPECT_TRUE(notMatches(
364 "namespace N {"
365 " namespace M {"
366 " class D {};"
367 " }"
368 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000369 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()))))));
Samuel Benzaquend93fcc12014-10-27 20:58:44 +0000378
379 EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000380}
381
Samuel Benzaquenef621f42015-02-10 14:46:45 +0000382TEST(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
Manuel Klimek94ad0bf2014-09-04 08:51:06 +0000397TEST(DeclarationMatcher, LinkageSpecification) {
398 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
399 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
400}
401
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000402TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000403 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000404 EXPECT_TRUE(notMatches("class X;", ClassX));
405 EXPECT_TRUE(notMatches("class X {};", ClassX));
406}
407
408TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000409 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000410 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
411 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
412}
413
414TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
415 EXPECT_TRUE(notMatches("template<typename T> class X { };"
416 "template<> class X<int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000417 classTemplateDecl(hasName("X"),
418 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000419}
420
421TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
422 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
423 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000424 classTemplateDecl(hasName("X"),
425 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000426}
427
Daniel Jasper4e566c42012-07-12 08:50:38 +0000428TEST(AllOf, AllOverloadsWork) {
429 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000430 "struct T { };"
431 "int f(int, T*, int, int);"
432 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000433 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000434 callExpr(allOf(callee(functionDecl(hasName("f"))),
435 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000436 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000437 callExpr(allOf(callee(functionDecl(hasName("f"))),
438 hasArgument(0, declRefExpr(to(varDecl()))),
439 hasArgument(1, hasType(pointsTo(
440 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000441 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)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000454}
455
Samuel Benzaquenb063f5c2015-07-17 16:05:27 +0000456TEST(ConstructVariadic, MismatchedTypes_Regression) {
457 EXPECT_TRUE(
458 matches("const int a = 0;",
459 internal::DynTypedMatcher::constructVariadic(
460 internal::DynTypedMatcher::VO_AnyOf,
461 ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>(),
462 {isConstQualified(), arrayType()})
463 .convertTo<QualType>()));
464}
465
Manuel Klimek04616e42012-07-06 05:48:52 +0000466TEST(DeclarationMatcher, MatchAnyOf) {
Aaron Ballman512fb642015-09-17 13:30:52 +0000467 DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
468 anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
469 EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
Manuel Klimek04616e42012-07-06 05:48:52 +0000470 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
471 EXPECT_TRUE(
472 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
473 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
474
Daniel Jasper84c763e2012-07-15 19:57:12 +0000475 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000476 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000477 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
478 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
479
Manuel Klimek04616e42012-07-06 05:48:52 +0000480 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000481 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
482 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000483 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
484 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
485 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
486 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
487 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
488 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000489
490 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
491 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
492 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
493 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Aaron Ballman8f4699a2015-07-02 14:02:41 +0000494
495 EXPECT_TRUE(
496 matches("void f() try { } catch (int) { } catch (...) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +0000497 cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000498}
499
500TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000501 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000502 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
503 EXPECT_TRUE(matches("class X {};", HasClassX));
504
505 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000506 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000507 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
508 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
509 EXPECT_TRUE(
510 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
511}
512
513TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
514 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000515 recordDecl(
516 has(recordDecl(
517 has(recordDecl(hasName("X"))),
518 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000519 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000520 has(recordDecl(
521 has(recordDecl(hasName("A"))),
522 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000523 hasName("C"))),
524 hasName("F"));
525
526 EXPECT_TRUE(matches(
527 "class F {"
528 " class Z {"
529 " class X {};"
530 " class Y {};"
531 " };"
532 " class C {"
533 " class A {};"
534 " class B {};"
535 " };"
536 "};", Recursive));
537
538 EXPECT_TRUE(matches(
539 "class F {"
540 " class Z {"
541 " class A {};"
542 " class X {};"
543 " class Y {};"
544 " };"
545 " class C {"
546 " class X {};"
547 " class A {};"
548 " class B {};"
549 " };"
550 "};", Recursive));
551
552 EXPECT_TRUE(matches(
553 "class O1 {"
554 " class O2 {"
555 " class F {"
556 " class Z {"
557 " class A {};"
558 " class X {};"
559 " class Y {};"
560 " };"
561 " class C {"
562 " class X {};"
563 " class A {};"
564 " class B {};"
565 " };"
566 " };"
567 " };"
568 "};", Recursive));
569}
570
571TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
572 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000573 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000574 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000575 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000576 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000577 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000578 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000579 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000580 hasName("Y"))),
581 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000582 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000583 anyOf(
584 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000585 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000586 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000587 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000588 hasName("B")))))),
589 hasName("F")));
590
591 EXPECT_TRUE(matches("class F {};", Recursive));
592 EXPECT_TRUE(matches("class Z {};", Recursive));
593 EXPECT_TRUE(matches("class C {};", Recursive));
594 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
595 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
596 EXPECT_TRUE(
597 matches("class O1 { class O2 {"
598 " class M { class N { class B {}; }; }; "
599 "}; };", Recursive));
600}
601
602TEST(DeclarationMatcher, MatchNot) {
603 DeclarationMatcher NotClassX =
Aaron Ballman512fb642015-09-17 13:30:52 +0000604 cxxRecordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000605 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000606 unless(hasName("X")));
607 EXPECT_TRUE(notMatches("", NotClassX));
608 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
609 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
610 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
611 EXPECT_TRUE(
612 notMatches("class Y {}; class Z {}; class X : public Y {};",
613 NotClassX));
614
615 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000616 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000617 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000618 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000619 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000620 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000621 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
622 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
623 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000624
625 DeclarationMatcher NamedNotRecord =
626 namedDecl(hasName("Foo"), unless(recordDecl()));
627 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
628 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000629}
630
631TEST(DeclarationMatcher, HasDescendant) {
632 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000633 recordDecl(
634 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000635 hasName("Z"));
636 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
637 EXPECT_TRUE(
638 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
639 EXPECT_TRUE(
640 matches("class Z { class A { class Y { class X {}; }; }; };",
641 ZDescendantClassX));
642 EXPECT_TRUE(
643 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
644 ZDescendantClassX));
645 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
646
647 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000648 recordDecl(
649 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000650 hasName("X"))),
651 hasName("Z"));
652 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
653 ZDescendantClassXHasClassY));
654 EXPECT_TRUE(
655 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
656 ZDescendantClassXHasClassY));
657 EXPECT_TRUE(notMatches(
658 "class Z {"
659 " class A {"
660 " class B {"
661 " class X {"
662 " class C {"
663 " class Y {};"
664 " };"
665 " };"
666 " }; "
667 " };"
668 "};", ZDescendantClassXHasClassY));
669
670 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000671 recordDecl(
672 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
673 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000674 hasName("Z"));
675 EXPECT_TRUE(
676 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
677 ZDescendantClassXDescendantClassY));
678 EXPECT_TRUE(matches(
679 "class Z {"
680 " class A {"
681 " class X {"
682 " class B {"
683 " class Y {};"
684 " };"
685 " class Y {};"
686 " };"
687 " };"
688 "};", ZDescendantClassXDescendantClassY));
689}
690
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000691TEST(DeclarationMatcher, HasDescendantMemoization) {
692 DeclarationMatcher CannotMemoize =
693 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
694 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
695}
696
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000697TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
698 auto Name = hasName("i");
699 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
700 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
701 // Matching VD first should not make a cache hit for RD.
702 EXPECT_TRUE(notMatches("void f() { int i; }",
703 decl(hasDescendant(VD), hasDescendant(RD))));
704 EXPECT_TRUE(notMatches("void f() { int i; }",
705 decl(hasDescendant(RD), hasDescendant(VD))));
706 // Not matching RD first should not make a cache hit for VD either.
707 EXPECT_TRUE(matches("void f() { int i; }",
708 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
709}
710
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000711TEST(DeclarationMatcher, HasAttr) {
712 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
713 decl(hasAttr(clang::attr::WarnUnused))));
714 EXPECT_FALSE(matches("struct X {};",
715 decl(hasAttr(clang::attr::WarnUnused))));
716}
717
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000718TEST(DeclarationMatcher, MatchCudaDecl) {
719 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
720 "void g() { f<<<1, 2>>>(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +0000721 cudaKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000722 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000723 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000724 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Aaron Ballman512fb642015-09-17 13:30:52 +0000725 cudaKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000726 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000727 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000728}
729
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000730// Implements a run method that returns whether BoundNodes contains a
731// Decl bound to Id that can be dynamically cast to T.
732// Optionally checks that the check succeeded a specific number of times.
733template <typename T>
734class VerifyIdIsBoundTo : public BoundNodesCallback {
735public:
736 // Create an object that checks that a node of type \c T was bound to \c Id.
737 // Does not check for a certain number of matches.
738 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
739 : Id(Id), ExpectedCount(-1), Count(0) {}
740
741 // Create an object that checks that a node of type \c T was bound to \c Id.
742 // Checks that there were exactly \c ExpectedCount matches.
743 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
744 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
745
746 // Create an object that checks that a node of type \c T was bound to \c Id.
747 // Checks that there was exactly one match with the name \c ExpectedName.
748 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000749 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
750 int ExpectedCount = 1)
751 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
752 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000753
Craig Toppera798a9d2014-03-02 09:32:10 +0000754 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000755 if (ExpectedCount != -1)
756 EXPECT_EQ(ExpectedCount, Count);
757 if (!ExpectedName.empty())
758 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000759 Count = 0;
760 Name.clear();
761 }
762
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000763 ~VerifyIdIsBoundTo() override {
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000764 EXPECT_EQ(0, Count);
765 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000766 }
767
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000768 bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000769 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000770 if (Nodes->getNodeAs<T>(Id)) {
771 ++Count;
772 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
773 Name = Named->getNameAsString();
774 } else if (const NestedNameSpecifier *NNS =
775 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
776 llvm::raw_string_ostream OS(Name);
777 NNS->print(OS, PrintingPolicy(LangOptions()));
778 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000779 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
780 EXPECT_NE(M.end(), I);
781 if (I != M.end())
782 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000783 return true;
784 }
Craig Topper416fa342014-06-08 08:38:12 +0000785 EXPECT_TRUE(M.count(Id) == 0 ||
786 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000787 return false;
788 }
789
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000790 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000791 return run(Nodes);
792 }
793
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000794private:
795 const std::string Id;
796 const int ExpectedCount;
797 int Count;
798 const std::string ExpectedName;
799 std::string Name;
800};
801
802TEST(HasDescendant, MatchesDescendantTypes) {
803 EXPECT_TRUE(matches("void f() { int i = 3; }",
804 decl(hasDescendant(loc(builtinType())))));
805 EXPECT_TRUE(matches("void f() { int i = 3; }",
806 stmt(hasDescendant(builtinType()))));
807
808 EXPECT_TRUE(matches("void f() { int i = 3; }",
809 stmt(hasDescendant(loc(builtinType())))));
810 EXPECT_TRUE(matches("void f() { int i = 3; }",
811 stmt(hasDescendant(qualType(builtinType())))));
812
813 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
814 stmt(hasDescendant(isInteger()))));
815
816 EXPECT_TRUE(matchAndVerifyResultTrue(
817 "void f() { int a; float c; int d; int e; }",
818 functionDecl(forEachDescendant(
819 varDecl(hasDescendant(isInteger())).bind("x"))),
820 new VerifyIdIsBoundTo<Decl>("x", 3)));
821}
822
823TEST(HasDescendant, MatchesDescendantsOfTypes) {
824 EXPECT_TRUE(matches("void f() { int*** i; }",
825 qualType(hasDescendant(builtinType()))));
826 EXPECT_TRUE(matches("void f() { int*** i; }",
827 qualType(hasDescendant(
828 pointerType(pointee(builtinType()))))));
829 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000830 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000831
832 EXPECT_TRUE(matchAndVerifyResultTrue(
833 "void f() { int*** i; }",
834 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
835 new VerifyIdIsBoundTo<Type>("x", 2)));
836}
837
838TEST(Has, MatchesChildrenOfTypes) {
839 EXPECT_TRUE(matches("int i;",
840 varDecl(hasName("i"), has(isInteger()))));
841 EXPECT_TRUE(notMatches("int** i;",
842 varDecl(hasName("i"), has(isInteger()))));
843 EXPECT_TRUE(matchAndVerifyResultTrue(
844 "int (*f)(float, int);",
845 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
846 new VerifyIdIsBoundTo<QualType>("x", 2)));
847}
848
849TEST(Has, MatchesChildTypes) {
850 EXPECT_TRUE(matches(
851 "int* i;",
852 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
853 EXPECT_TRUE(notMatches(
854 "int* i;",
855 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
856}
857
Samuel Benzaquenc640ef52014-10-28 13:33:58 +0000858TEST(ValueDecl, Matches) {
859 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
860 valueDecl(hasType(asString("enum EnumType")))));
861 EXPECT_TRUE(matches("void FunctionDecl();",
862 valueDecl(hasType(asString("void (void)")))));
863}
864
Daniel Jasper1dad1832012-07-10 20:20:19 +0000865TEST(Enum, DoesNotMatchClasses) {
866 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
867}
868
869TEST(Enum, MatchesEnums) {
870 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
871}
872
873TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000874 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000875 EXPECT_TRUE(matches("enum X{ A };", Matcher));
876 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
877 EXPECT_TRUE(notMatches("enum X {};", Matcher));
878}
879
Manuel Klimek04616e42012-07-06 05:48:52 +0000880TEST(StatementMatcher, Has) {
881 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000882 expr(hasType(pointsTo(recordDecl(hasName("X")))),
883 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000884
885 EXPECT_TRUE(matches(
886 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
887 EXPECT_TRUE(notMatches(
888 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
889}
890
891TEST(StatementMatcher, HasDescendant) {
892 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000893 expr(hasType(pointsTo(recordDecl(hasName("X")))),
894 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000895
896 EXPECT_TRUE(matches(
897 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
898 HasDescendantVariableI));
899 EXPECT_TRUE(notMatches(
900 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
901 HasDescendantVariableI));
902}
903
904TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000905 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000906
907 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
908 EXPECT_TRUE(notMatches("class A {};", TypeA));
909
Aaron Ballman512fb642015-09-17 13:30:52 +0000910 TypeMatcher TypeDerivedFromA =
911 hasDeclaration(cxxRecordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000912
913 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
914 TypeDerivedFromA));
915 EXPECT_TRUE(notMatches("class A {};", TypeA));
916
917 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000918 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000919
920 EXPECT_TRUE(
921 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
Aaron Ballmanc129c692015-09-04 18:34:48 +0000922
923 EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }",
924 varDecl(hasType(namedDecl(hasName("S"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000925}
926
Aaron Ballmanb85be662015-09-11 11:51:24 +0000927TEST(TypeMatcher, MatchesDeclTypes) {
928 // TypedefType -> TypedefNameDecl
929 EXPECT_TRUE(matches("typedef int I; void f(I i);",
930 parmVarDecl(hasType(namedDecl(hasName("I"))))));
931 // ObjCObjectPointerType
932 EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);",
933 parmVarDecl(hasType(objcObjectPointerType()))));
934 // ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl
935 EXPECT_TRUE(matchesObjC(
936 "@interface Foo @end void f(Foo *f);",
937 parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo")))))));
938 // TemplateTypeParmType
939 EXPECT_TRUE(matches("template <typename T> void f(T t);",
940 parmVarDecl(hasType(templateTypeParmType()))));
941 // TemplateTypeParmType -> TemplateTypeParmDecl
942 EXPECT_TRUE(matches("template <typename T> void f(T t);",
943 parmVarDecl(hasType(namedDecl(hasName("T"))))));
944 // InjectedClassNameType
945 EXPECT_TRUE(matches("template <typename T> struct S {"
946 " void f(S s);"
947 "};",
948 parmVarDecl(hasType(injectedClassNameType()))));
949 EXPECT_TRUE(notMatches("template <typename T> struct S {"
950 " void g(S<T> s);"
951 "};",
952 parmVarDecl(hasType(injectedClassNameType()))));
953 // InjectedClassNameType -> CXXRecordDecl
954 EXPECT_TRUE(matches("template <typename T> struct S {"
955 " void f(S s);"
956 "};",
957 parmVarDecl(hasType(namedDecl(hasName("S"))))));
958
959 static const char Using[] = "template <typename T>"
960 "struct Base {"
961 " typedef T Foo;"
962 "};"
963 ""
964 "template <typename T>"
965 "struct S : private Base<T> {"
966 " using typename Base<T>::Foo;"
967 " void f(Foo);"
968 "};";
969 // UnresolvedUsingTypenameDecl
970 EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo"))));
971 // UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl
972 EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo"))))));
973}
974
Manuel Klimek04616e42012-07-06 05:48:52 +0000975TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000976 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000977
978 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000979 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000980
981 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000982 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000983
984 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000985 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000986
987 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
988 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000989 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000990
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000991 StatementMatcher MethodX =
Aaron Ballman512fb642015-09-17 13:30:52 +0000992 callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000993
994 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
995 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000996 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000997}
998
999TEST(Matcher, BindTheSameNameInAlternatives) {
1000 StatementMatcher matcher = anyOf(
1001 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001002 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +00001003 hasRHS(integerLiteral(equals(0)))),
1004 binaryOperator(hasOperatorName("+"),
1005 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001006 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001007
1008 EXPECT_TRUE(matchAndVerifyResultTrue(
1009 // The first branch of the matcher binds x to 0 but then fails.
1010 // The second branch binds x to f() and succeeds.
1011 "int f() { return 0 + f(); }",
1012 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00001013 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001014}
1015
Manuel Klimekfdf98762012-08-30 19:41:06 +00001016TEST(Matcher, BindsIDForMemoizedResults) {
1017 // Using the same matcher in two match expressions will make memoization
1018 // kick in.
1019 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
1020 EXPECT_TRUE(matchAndVerifyResultTrue(
1021 "class A { class B { class X {}; }; };",
1022 DeclarationMatcher(anyOf(
1023 recordDecl(hasName("A"), hasDescendant(ClassX)),
1024 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00001025 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +00001026}
1027
Daniel Jasper856194d02012-12-03 15:43:25 +00001028TEST(HasDeclaration, HasDeclarationOfEnumType) {
1029 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
1030 expr(hasType(pointsTo(
1031 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
1032}
1033
Edwin Vaneed936452013-02-25 14:32:42 +00001034TEST(HasDeclaration, HasGetDeclTraitTest) {
1035 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
1036 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
1037 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
1038}
1039
Edwin Vane2c197e02013-02-19 17:14:34 +00001040TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
1041 EXPECT_TRUE(matches("typedef int X; X a;",
1042 varDecl(hasName("a"),
1043 hasType(typedefType(hasDeclaration(decl()))))));
1044
1045 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
1046}
1047
Edwin Vanef901b712013-02-25 14:49:29 +00001048TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
1049 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
1050 varDecl(hasType(templateSpecializationType(
1051 hasDeclaration(namedDecl(hasName("A"))))))));
1052}
1053
Manuel Klimek04616e42012-07-06 05:48:52 +00001054TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001055 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001056 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001057 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001058 EXPECT_TRUE(
1059 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001060 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001061 EXPECT_TRUE(
1062 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001063 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001064}
1065
1066TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001067 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001068 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001069 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001070 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001071 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001072 EXPECT_TRUE(
1073 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001074 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001075}
1076
1077TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001078 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001079 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001080 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001081 EXPECT_TRUE(
1082 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001083 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001084}
1085
1086TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001087 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001088 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001089 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001090 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001091 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001092}
1093
Manuel Klimekc16c6522013-06-20 13:08:29 +00001094TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1095 EXPECT_TRUE(matches("int x;",
1096 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1097
1098 // Make sure we don't crash on implicit constructors.
1099 EXPECT_TRUE(notMatches("class X {}; X x;",
1100 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1101}
1102
Manuel Klimek04616e42012-07-06 05:48:52 +00001103TEST(Matcher, Call) {
1104 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001105 // Matcher<Decl>, too?
Aaron Ballman512fb642015-09-17 13:30:52 +00001106 StatementMatcher MethodX =
1107 callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001108
1109 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1110 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1111
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001112 StatementMatcher MethodOnY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001113 cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001114
1115 EXPECT_TRUE(
1116 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1117 MethodOnY));
1118 EXPECT_TRUE(
1119 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1120 MethodOnY));
1121 EXPECT_TRUE(
1122 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1123 MethodOnY));
1124 EXPECT_TRUE(
1125 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1126 MethodOnY));
1127 EXPECT_TRUE(
1128 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1129 MethodOnY));
1130
1131 StatementMatcher MethodOnYPointer =
Aaron Ballman512fb642015-09-17 13:30:52 +00001132 cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001133
1134 EXPECT_TRUE(
1135 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1136 MethodOnYPointer));
1137 EXPECT_TRUE(
1138 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1139 MethodOnYPointer));
1140 EXPECT_TRUE(
1141 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1142 MethodOnYPointer));
1143 EXPECT_TRUE(
1144 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1145 MethodOnYPointer));
1146 EXPECT_TRUE(
1147 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1148 MethodOnYPointer));
1149}
1150
Daniel Jasper5901e472012-10-01 13:40:41 +00001151TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001152 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001153 lambdaExpr()));
1154}
1155
1156TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001157 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1158 "void f() { for (auto &a : as); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001159 cxxForRangeStmt()));
Daniel Jasper5901e472012-10-01 13:40:41 +00001160 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001161 cxxForRangeStmt()));
Daniel Jasper5901e472012-10-01 13:40:41 +00001162}
1163
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001164TEST(Matcher, SubstNonTypeTemplateParm) {
1165 EXPECT_FALSE(matches("template<int N>\n"
1166 "struct A { static const int n = 0; };\n"
1167 "struct B : public A<42> {};",
1168 substNonTypeTemplateParmExpr()));
1169 EXPECT_TRUE(matches("template<int N>\n"
1170 "struct A { static const int n = N; };\n"
1171 "struct B : public A<42> {};",
1172 substNonTypeTemplateParmExpr()));
1173}
1174
Aaron Ballman478a8eb2015-10-05 19:44:42 +00001175TEST(Matcher, NonTypeTemplateParmDecl) {
1176 EXPECT_TRUE(matches("template <int N> void f();",
1177 nonTypeTemplateParmDecl(hasName("N"))));
1178 EXPECT_TRUE(
1179 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
1180}
1181
Eric Fiselier3acf5fd2015-10-17 02:34:44 +00001182TEST(Matcher, templateTypeParmDecl) {
1183 EXPECT_TRUE(matches("template <typename T> void f();",
1184 templateTypeParmDecl(hasName("T"))));
1185 EXPECT_TRUE(
1186 notMatches("template <int N> void f();", templateTypeParmDecl()));
1187}
1188
Daniel Jasper5901e472012-10-01 13:40:41 +00001189TEST(Matcher, UserDefinedLiteral) {
1190 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1191 " return i + 1;"
1192 "}"
1193 "char c = 'a'_inc;",
1194 userDefinedLiteral()));
1195}
1196
Daniel Jasper87c3d362012-09-20 14:12:57 +00001197TEST(Matcher, FlowControl) {
1198 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1199 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1200 continueStmt()));
1201 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1202 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1203 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1204}
1205
Daniel Jasper1dad1832012-07-10 20:20:19 +00001206TEST(HasType, MatchesAsString) {
1207 EXPECT_TRUE(
1208 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001209 cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
1210 EXPECT_TRUE(
1211 matches("class X { void x(int x) {} };",
1212 cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001213 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001214 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001215 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001216 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001217}
1218
Manuel Klimek04616e42012-07-06 05:48:52 +00001219TEST(Matcher, OverloadedOperatorCall) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001220 StatementMatcher OpCall = cxxOperatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001221 // Unary operator
1222 EXPECT_TRUE(matches("class Y { }; "
1223 "bool operator!(Y x) { return false; }; "
1224 "Y y; bool c = !y;", OpCall));
1225 // No match -- special operators like "new", "delete"
1226 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1227 // we need to figure out include paths in the test.
1228 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1229 // "class Y { }; "
1230 // "void *operator new(size_t size) { return 0; } "
1231 // "Y *y = new Y;", OpCall));
1232 EXPECT_TRUE(notMatches("class Y { }; "
1233 "void operator delete(void *p) { } "
1234 "void a() {Y *y = new Y; delete y;}", OpCall));
1235 // Binary operator
1236 EXPECT_TRUE(matches("class Y { }; "
1237 "bool operator&&(Y x, Y y) { return true; }; "
1238 "Y a; Y b; bool c = a && b;",
1239 OpCall));
1240 // No match -- normal operator, not an overloaded one.
1241 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1242 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1243}
1244
1245TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1246 StatementMatcher OpCallAndAnd =
Aaron Ballman512fb642015-09-17 13:30:52 +00001247 cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001248 EXPECT_TRUE(matches("class Y { }; "
1249 "bool operator&&(Y x, Y y) { return true; }; "
1250 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1251 StatementMatcher OpCallLessLess =
Aaron Ballman512fb642015-09-17 13:30:52 +00001252 cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001253 EXPECT_TRUE(notMatches("class Y { }; "
1254 "bool operator&&(Y x, Y y) { return true; }; "
1255 "Y a; Y b; bool c = a && b;",
1256 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001257 StatementMatcher OpStarCall =
Aaron Ballman512fb642015-09-17 13:30:52 +00001258 cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
Benjamin Kramer09514492014-07-14 14:05:02 +00001259 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1260 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001261 DeclarationMatcher ClassWithOpStar =
Aaron Ballman512fb642015-09-17 13:30:52 +00001262 cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001263 EXPECT_TRUE(matches("class Y { int operator*(); };",
1264 ClassWithOpStar));
1265 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1266 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001267 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1268 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1269 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001270}
1271
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001272TEST(Matcher, NestedOverloadedOperatorCalls) {
1273 EXPECT_TRUE(matchAndVerifyResultTrue(
Aaron Ballman512fb642015-09-17 13:30:52 +00001274 "class Y { }; "
1275 "Y& operator&&(Y& x, Y& y) { return x; }; "
1276 "Y a; Y b; Y c; Y d = a && b && c;",
1277 cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1278 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1279 EXPECT_TRUE(matches("class Y { }; "
1280 "Y& operator&&(Y& x, Y& y) { return x; }; "
1281 "Y a; Y b; Y c; Y d = a && b && c;",
1282 cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
1283 EXPECT_TRUE(
1284 matches("class Y { }; "
1285 "Y& operator&&(Y& x, Y& y) { return x; }; "
1286 "Y a; Y b; Y c; Y d = a && b && c;",
1287 cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001288}
1289
Manuel Klimek04616e42012-07-06 05:48:52 +00001290TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001291 StatementMatcher MethodOnY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001292 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001293
1294 EXPECT_TRUE(
1295 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1296 MethodOnY));
1297 EXPECT_TRUE(
1298 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1299 MethodOnY));
1300 EXPECT_TRUE(
1301 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1302 MethodOnY));
1303 EXPECT_TRUE(
1304 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1305 MethodOnY));
1306 EXPECT_TRUE(
1307 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1308 MethodOnY));
1309
1310 EXPECT_TRUE(matches(
1311 "class Y {"
1312 " public: virtual void x();"
1313 "};"
1314 "class X : public Y {"
1315 " public: virtual void x();"
1316 "};"
1317 "void z() { X *x; x->Y::x(); }", MethodOnY));
1318}
1319
1320TEST(Matcher, VariableUsage) {
1321 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001322 declRefExpr(to(
1323 varDecl(hasInitializer(
Aaron Ballman512fb642015-09-17 13:30:52 +00001324 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001325
1326 EXPECT_TRUE(matches(
1327 "class Y {"
1328 " public:"
1329 " bool x() const;"
1330 "};"
1331 "void z(const Y &y) {"
1332 " bool b = y.x();"
1333 " if (b) {}"
1334 "}", Reference));
1335
1336 EXPECT_TRUE(notMatches(
1337 "class Y {"
1338 " public:"
1339 " bool x() const;"
1340 "};"
1341 "void z(const Y &y) {"
1342 " bool b = y.x();"
1343 "}", Reference));
1344}
1345
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001346TEST(Matcher, VarDecl_Storage) {
1347 auto M = varDecl(hasName("X"), hasLocalStorage());
1348 EXPECT_TRUE(matches("void f() { int X; }", M));
1349 EXPECT_TRUE(notMatches("int X;", M));
1350 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1351
1352 M = varDecl(hasName("X"), hasGlobalStorage());
1353 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1354 EXPECT_TRUE(matches("int X;", M));
1355 EXPECT_TRUE(matches("void f() { static int X; }", M));
1356}
1357
Manuel Klimek61379422012-12-04 14:42:08 +00001358TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001359 EXPECT_TRUE(matches(
1360 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001361 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001362}
1363
Manuel Klimek04616e42012-07-06 05:48:52 +00001364TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001365 StatementMatcher CallOnVariableY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001366 cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001367
1368 EXPECT_TRUE(matches(
1369 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1370 EXPECT_TRUE(matches(
1371 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1372 EXPECT_TRUE(matches(
1373 "class Y { public: void x(); };"
1374 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1375 EXPECT_TRUE(matches(
1376 "class Y { public: void x(); };"
1377 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1378 EXPECT_TRUE(notMatches(
1379 "class Y { public: void x(); };"
1380 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1381 CallOnVariableY));
1382}
1383
Daniel Jasper1dad1832012-07-10 20:20:19 +00001384TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1385 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1386 unaryExprOrTypeTraitExpr()));
1387 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1388 alignOfExpr(anything())));
1389 // FIXME: Uncomment once alignof is enabled.
1390 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1391 // unaryExprOrTypeTraitExpr()));
1392 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1393 // sizeOfExpr()));
1394}
1395
1396TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1397 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1398 hasArgumentOfType(asString("int")))));
1399 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1400 hasArgumentOfType(asString("float")))));
1401 EXPECT_TRUE(matches(
1402 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001403 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001404 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001405 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001406}
1407
Manuel Klimek04616e42012-07-06 05:48:52 +00001408TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001409 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001410}
1411
1412TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001413 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001414}
1415
1416TEST(MemberExpression, MatchesVariable) {
1417 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001418 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001419 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001420 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001421 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001422 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001423}
1424
1425TEST(MemberExpression, MatchesStaticVariable) {
1426 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001427 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001428 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001429 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001430 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001431 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001432}
1433
Daniel Jasper4e566c42012-07-12 08:50:38 +00001434TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001435 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1436 EXPECT_TRUE(matches(
1437 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1438 callExpr(hasArgument(0, declRefExpr(
1439 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001440}
1441
1442TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001443 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001444 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001445 callExpr(hasArgument(0, declRefExpr(
1446 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001447}
1448
Manuel Klimek04616e42012-07-06 05:48:52 +00001449TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1450 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001451 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001452 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001453 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001454 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001455 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001456}
1457
1458TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1459 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001460 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001461 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001462 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001463 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001464 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001465}
1466
1467TEST(IsArrow, MatchesMemberCallsViaArrow) {
1468 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001469 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001470 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001471 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001472 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001473 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001474}
1475
1476TEST(Callee, MatchesDeclarations) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001477 StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001478
1479 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1480 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001481
Aaron Ballman512fb642015-09-17 13:30:52 +00001482 CallMethodX = callExpr(callee(cxxConversionDecl()));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001483 EXPECT_TRUE(
1484 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1485 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1486 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001487}
1488
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001489TEST(ConversionDeclaration, IsExplicit) {
1490 EXPECT_TRUE(matches("struct S { explicit operator int(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001491 cxxConversionDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001492 EXPECT_TRUE(notMatches("struct S { operator int(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001493 cxxConversionDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001494}
1495
Manuel Klimek04616e42012-07-06 05:48:52 +00001496TEST(Callee, MatchesMemberExpressions) {
1497 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001498 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001499 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001500 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001501}
1502
1503TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001504 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001505
1506 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1507 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1508
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001509 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1510 llvm::Triple::Win32) {
1511 // FIXME: Make this work for MSVC.
1512 // Dependent contexts, but a non-dependent call.
1513 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1514 CallFunctionF));
1515 EXPECT_TRUE(
1516 matches("void f(); template <int N> struct S { void g() { f(); } };",
1517 CallFunctionF));
1518 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001519
1520 // Depedent calls don't match.
1521 EXPECT_TRUE(
1522 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1523 CallFunctionF));
1524 EXPECT_TRUE(
1525 notMatches("void f(int);"
1526 "template <typename T> struct S { void g(T t) { f(t); } };",
1527 CallFunctionF));
Aaron Ballman3fd6c112015-10-05 14:41:27 +00001528
1529 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
1530 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
1531 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
1532 functionDecl(isVariadic())));
1533 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
1534 EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001535}
1536
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001537TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1538 EXPECT_TRUE(
1539 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001540 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001541}
1542
1543TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1544 EXPECT_TRUE(
1545 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001546 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001547}
1548
1549TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1550 EXPECT_TRUE(
1551 notMatches("void g(); template <typename T> void f(T t) {}"
1552 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001553 functionTemplateDecl(hasName("f"),
1554 hasDescendant(declRefExpr(to(
1555 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001556}
1557
Manuel Klimek04616e42012-07-06 05:48:52 +00001558TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001559 StatementMatcher CallArgumentY = callExpr(
1560 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001561
1562 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1563 EXPECT_TRUE(
1564 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1565 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1566
Daniel Jasper848cbe12012-09-18 13:09:13 +00001567 StatementMatcher WrongIndex = callExpr(
1568 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001569 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1570}
1571
1572TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001573 StatementMatcher CallArgumentY = callExpr(
1574 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001575 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1576 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1577 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1578}
1579
1580TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001581 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001582
1583 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1584 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1585 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1586}
1587
Daniel Jasper9f501292012-12-04 11:54:27 +00001588TEST(Matcher, ParameterCount) {
1589 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1590 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1591 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1592 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1593 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1594}
1595
Manuel Klimek04616e42012-07-06 05:48:52 +00001596TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001597 DeclarationMatcher ReferenceClassX = varDecl(
1598 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001599 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1600 ReferenceClassX));
1601 EXPECT_TRUE(
1602 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001603 // The match here is on the implicit copy constructor code for
1604 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001605 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001606 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1607 EXPECT_TRUE(
1608 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001609 EXPECT_TRUE(
1610 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1611}
1612
Edwin Vane0a4836e2013-03-06 17:02:57 +00001613TEST(QualType, hasCanonicalType) {
1614 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1615 "int a;"
1616 "int_ref b = a;",
1617 varDecl(hasType(qualType(referenceType())))));
1618 EXPECT_TRUE(
1619 matches("typedef int &int_ref;"
1620 "int a;"
1621 "int_ref b = a;",
1622 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1623}
1624
Edwin Vane119d3df2013-04-02 18:15:55 +00001625TEST(QualType, hasLocalQualifiers) {
1626 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1627 varDecl(hasType(hasLocalQualifiers()))));
1628 EXPECT_TRUE(matches("int *const j = nullptr;",
1629 varDecl(hasType(hasLocalQualifiers()))));
1630 EXPECT_TRUE(matches("int *volatile k;",
1631 varDecl(hasType(hasLocalQualifiers()))));
1632 EXPECT_TRUE(notMatches("int m;",
1633 varDecl(hasType(hasLocalQualifiers()))));
1634}
1635
Manuel Klimek04616e42012-07-06 05:48:52 +00001636TEST(HasParameter, CallsInnerMatcher) {
1637 EXPECT_TRUE(matches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001638 cxxMethodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001639 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001640 cxxMethodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001641}
1642
1643TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1644 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001645 cxxMethodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001646}
1647
1648TEST(HasType, MatchesParameterVariableTypesStrictly) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001649 EXPECT_TRUE(matches(
1650 "class X { void x(X x) {} };",
1651 cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
1652 EXPECT_TRUE(notMatches(
1653 "class X { void x(const X &x) {} };",
1654 cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001655 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001656 cxxMethodDecl(hasParameter(
1657 0, hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001658 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001659 cxxMethodDecl(hasParameter(
1660 0, hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001661}
1662
1663TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001664 EXPECT_TRUE(matches(
1665 "class Y {}; class X { void x(X x, Y y) {} };",
1666 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
1667 EXPECT_TRUE(matches(
1668 "class Y {}; class X { void x(Y y, X x) {} };",
1669 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001670}
1671
Daniel Jasper1dad1832012-07-10 20:20:19 +00001672TEST(Returns, MatchesReturnTypes) {
1673 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001674 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001675 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001676 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001677 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001678 functionDecl(returns(hasDeclaration(
1679 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001680}
1681
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001682TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001683 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1684 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1685 functionDecl(isExternC())));
1686 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001687}
1688
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001689TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1690 EXPECT_TRUE(
1691 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1692 EXPECT_TRUE(matches("void Func() = delete;",
1693 functionDecl(hasName("Func"), isDeleted())));
1694}
1695
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001696TEST(isConstexpr, MatchesConstexprDeclarations) {
1697 EXPECT_TRUE(matches("constexpr int foo = 42;",
1698 varDecl(hasName("foo"), isConstexpr())));
1699 EXPECT_TRUE(matches("constexpr int bar();",
1700 functionDecl(hasName("bar"), isConstexpr())));
1701}
1702
Manuel Klimek04616e42012-07-06 05:48:52 +00001703TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001704 EXPECT_TRUE(notMatches(
1705 "class Y {}; class X { void x(int) {} };",
1706 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001707}
1708
1709TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1710 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001711 cxxMethodDecl(hasAnyParameter(
1712 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001713}
1714
Alp Toker8db6e7a2014-01-05 06:38:57 +00001715TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001716 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001717 cxxMethodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001718 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001719 cxxMethodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001720}
1721
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001722TEST(Matcher, MatchesClassTemplateSpecialization) {
1723 EXPECT_TRUE(matches("template<typename T> struct A {};"
1724 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001725 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001726 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001727 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001728 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001729 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001730}
1731
Manuel Klimekc16c6522013-06-20 13:08:29 +00001732TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1733 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1734 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1735}
1736
1737TEST(ParmVarDecl, MatchesParmVars) {
1738 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1739 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1740}
1741
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001742TEST(Matcher, MatchesTypeTemplateArgument) {
1743 EXPECT_TRUE(matches(
1744 "template<typename T> struct B {};"
1745 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001746 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001747 asString("int"))))));
1748}
1749
1750TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1751 EXPECT_TRUE(matches(
1752 "struct B { int next; };"
1753 "template<int(B::*next_ptr)> struct A {};"
1754 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001755 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1756 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001757
1758 EXPECT_TRUE(notMatches(
1759 "template <typename T> struct A {};"
1760 "A<int> a;",
1761 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1762 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001763
1764 EXPECT_TRUE(matches(
1765 "struct B { int next; };"
1766 "template<int(B::*next_ptr)> struct A {};"
1767 "A<&B::next> a;",
1768 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1769 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1770
1771 EXPECT_TRUE(notMatches(
1772 "template <typename T> struct A {};"
1773 "A<int> a;",
1774 templateSpecializationType(hasAnyTemplateArgument(
1775 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001776}
1777
1778TEST(Matcher, MatchesSpecificArgument) {
1779 EXPECT_TRUE(matches(
1780 "template<typename T, typename U> class A {};"
1781 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001782 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001783 1, refersToType(asString("int"))))));
1784 EXPECT_TRUE(notMatches(
1785 "template<typename T, typename U> class A {};"
1786 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001787 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001788 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001789
1790 EXPECT_TRUE(matches(
1791 "template<typename T, typename U> class A {};"
1792 "A<bool, int> a;",
1793 templateSpecializationType(hasTemplateArgument(
1794 1, refersToType(asString("int"))))));
1795 EXPECT_TRUE(notMatches(
1796 "template<typename T, typename U> class A {};"
1797 "A<int, bool> a;",
1798 templateSpecializationType(hasTemplateArgument(
1799 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001800}
1801
Manuel Klimek7735e402014-10-09 13:06:22 +00001802TEST(TemplateArgument, Matches) {
1803 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1804 classTemplateSpecializationDecl(
1805 hasAnyTemplateArgument(templateArgument()))));
1806 EXPECT_TRUE(matches(
1807 "template<typename T> struct C {}; C<int> c;",
1808 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1809}
1810
1811TEST(TemplateArgumentCountIs, Matches) {
1812 EXPECT_TRUE(
1813 matches("template<typename T> struct C {}; C<int> c;",
1814 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1815 EXPECT_TRUE(
1816 notMatches("template<typename T> struct C {}; C<int> c;",
1817 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1818
1819 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1820 templateSpecializationType(templateArgumentCountIs(1))));
1821 EXPECT_TRUE(
1822 notMatches("template<typename T> struct C {}; C<int> c;",
1823 templateSpecializationType(templateArgumentCountIs(2))));
1824}
1825
1826TEST(IsIntegral, Matches) {
1827 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1828 classTemplateSpecializationDecl(
1829 hasAnyTemplateArgument(isIntegral()))));
1830 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1831 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1832 templateArgument(isIntegral())))));
1833}
1834
1835TEST(RefersToIntegralType, Matches) {
1836 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1837 classTemplateSpecializationDecl(
1838 hasAnyTemplateArgument(refersToIntegralType(
1839 asString("int"))))));
1840 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1841 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1842 refersToIntegralType(asString("int"))))));
1843}
1844
1845TEST(EqualsIntegralValue, Matches) {
1846 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1847 classTemplateSpecializationDecl(
1848 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1849 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1850 classTemplateSpecializationDecl(
1851 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1852 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1853 classTemplateSpecializationDecl(
1854 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1855 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1856 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1857 equalsIntegralValue("0042")))));
1858}
1859
Daniel Jasper639522c2013-02-25 12:02:08 +00001860TEST(Matcher, MatchesAccessSpecDecls) {
1861 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1862 EXPECT_TRUE(
1863 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1864 EXPECT_TRUE(
1865 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1866 EXPECT_TRUE(
1867 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1868
1869 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1870}
1871
Aaron Ballman41143bb2015-07-24 12:35:41 +00001872TEST(Matcher, MatchesFinal) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001873 EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
Aaron Ballman41143bb2015-07-24 12:35:41 +00001874 EXPECT_TRUE(matches("class X { virtual void f() final; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001875 cxxMethodDecl(isFinal())));
1876 EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
1877 EXPECT_TRUE(
1878 notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
Aaron Ballman41143bb2015-07-24 12:35:41 +00001879}
1880
Edwin Vane37ee1d72013-04-09 20:46:36 +00001881TEST(Matcher, MatchesVirtualMethod) {
1882 EXPECT_TRUE(matches("class X { virtual int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001883 cxxMethodDecl(isVirtual(), hasName("::X::f"))));
1884 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001885}
1886
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001887TEST(Matcher, MatchesPureMethod) {
1888 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001889 cxxMethodDecl(isPure(), hasName("::X::f"))));
1890 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001891}
1892
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00001893TEST(Matcher, MatchesCopyAssignmentOperator) {
1894 EXPECT_TRUE(matches("class X { X &operator=(X); };",
1895 cxxMethodDecl(isCopyAssignmentOperator())));
1896 EXPECT_TRUE(matches("class X { X &operator=(X &); };",
1897 cxxMethodDecl(isCopyAssignmentOperator())));
1898 EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
1899 cxxMethodDecl(isCopyAssignmentOperator())));
1900 EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
1901 cxxMethodDecl(isCopyAssignmentOperator())));
1902 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
1903 cxxMethodDecl(isCopyAssignmentOperator())));
1904 EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
1905 cxxMethodDecl(isCopyAssignmentOperator())));
1906}
1907
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001908TEST(Matcher, MatchesConstMethod) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001909 EXPECT_TRUE(
1910 matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
1911 EXPECT_TRUE(
1912 notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001913}
1914
Edwin Vane37ee1d72013-04-09 20:46:36 +00001915TEST(Matcher, MatchesOverridingMethod) {
1916 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1917 "class Y : public X { int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001918 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001919 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
Aaron Ballman512fb642015-09-17 13:30:52 +00001920 "class Y : public X { int f(); };",
1921 cxxMethodDecl(isOverride(), hasName("::X::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001922 EXPECT_TRUE(notMatches("class X { int f(); }; "
1923 "class Y : public X { int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001924 cxxMethodDecl(isOverride())));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001925 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
Aaron Ballman512fb642015-09-17 13:30:52 +00001926 cxxMethodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001927 EXPECT_TRUE(
1928 matches("template <typename Base> struct Y : Base { void f() override;};",
Aaron Ballman512fb642015-09-17 13:30:52 +00001929 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001930}
1931
Manuel Klimek04616e42012-07-06 05:48:52 +00001932TEST(Matcher, ConstructorCall) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001933 StatementMatcher Constructor = cxxConstructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001934
1935 EXPECT_TRUE(
1936 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1937 EXPECT_TRUE(
1938 matches("class X { public: X(); }; void x() { X x = X(); }",
1939 Constructor));
1940 EXPECT_TRUE(
1941 matches("class X { public: X(int); }; void x() { X x = 0; }",
1942 Constructor));
1943 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1944}
1945
1946TEST(Matcher, ConstructorArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001947 StatementMatcher Constructor = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00001948 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001949
1950 EXPECT_TRUE(
1951 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1952 Constructor));
1953 EXPECT_TRUE(
1954 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1955 Constructor));
1956 EXPECT_TRUE(
1957 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1958 Constructor));
1959 EXPECT_TRUE(
1960 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1961 Constructor));
1962
Aaron Ballman512fb642015-09-17 13:30:52 +00001963 StatementMatcher WrongIndex = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00001964 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001965 EXPECT_TRUE(
1966 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1967 WrongIndex));
1968}
1969
1970TEST(Matcher, ConstructorArgumentCount) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001971 StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001972
1973 EXPECT_TRUE(
1974 matches("class X { public: X(int); }; void x() { X x(0); }",
1975 Constructor1Arg));
1976 EXPECT_TRUE(
1977 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1978 Constructor1Arg));
1979 EXPECT_TRUE(
1980 matches("class X { public: X(int); }; void x() { X x = 0; }",
1981 Constructor1Arg));
1982 EXPECT_TRUE(
1983 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1984 Constructor1Arg));
1985}
1986
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001987TEST(Matcher, ConstructorListInitialization) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001988 StatementMatcher ConstructorListInit =
1989 cxxConstructExpr(isListInitialization());
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001990
1991 EXPECT_TRUE(
1992 matches("class X { public: X(int); }; void x() { X x{0}; }",
1993 ConstructorListInit));
1994 EXPECT_FALSE(
1995 matches("class X { public: X(int); }; void x() { X x(0); }",
1996 ConstructorListInit));
1997}
1998
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001999TEST(Matcher,ThisExpr) {
2000 EXPECT_TRUE(
Aaron Ballman512fb642015-09-17 13:30:52 +00002001 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002002 EXPECT_TRUE(
Aaron Ballman512fb642015-09-17 13:30:52 +00002003 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002004}
2005
Manuel Klimek04616e42012-07-06 05:48:52 +00002006TEST(Matcher, BindTemporaryExpression) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002007 StatementMatcher TempExpression = cxxBindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002008
2009 std::string ClassString = "class string { public: string(); ~string(); }; ";
2010
2011 EXPECT_TRUE(
2012 matches(ClassString +
2013 "string GetStringByValue();"
2014 "void FunctionTakesString(string s);"
2015 "void run() { FunctionTakesString(GetStringByValue()); }",
2016 TempExpression));
2017
2018 EXPECT_TRUE(
2019 notMatches(ClassString +
2020 "string* GetStringPointer(); "
2021 "void FunctionTakesStringPtr(string* s);"
2022 "void run() {"
2023 " string* s = GetStringPointer();"
2024 " FunctionTakesStringPtr(GetStringPointer());"
2025 " FunctionTakesStringPtr(s);"
2026 "}",
2027 TempExpression));
2028
2029 EXPECT_TRUE(
2030 notMatches("class no_dtor {};"
2031 "no_dtor GetObjByValue();"
2032 "void ConsumeObj(no_dtor param);"
2033 "void run() { ConsumeObj(GetObjByValue()); }",
2034 TempExpression));
2035}
2036
Sam Panzer68a35af2012-08-24 22:04:44 +00002037TEST(MaterializeTemporaryExpr, MatchesTemporary) {
2038 std::string ClassString =
2039 "class string { public: string(); int length(); }; ";
2040
2041 EXPECT_TRUE(
2042 matches(ClassString +
2043 "string GetStringByValue();"
2044 "void FunctionTakesString(string s);"
2045 "void run() { FunctionTakesString(GetStringByValue()); }",
2046 materializeTemporaryExpr()));
2047
2048 EXPECT_TRUE(
2049 notMatches(ClassString +
2050 "string* GetStringPointer(); "
2051 "void FunctionTakesStringPtr(string* s);"
2052 "void run() {"
2053 " string* s = GetStringPointer();"
2054 " FunctionTakesStringPtr(GetStringPointer());"
2055 " FunctionTakesStringPtr(s);"
2056 "}",
2057 materializeTemporaryExpr()));
2058
2059 EXPECT_TRUE(
2060 notMatches(ClassString +
2061 "string GetStringByValue();"
2062 "void run() { int k = GetStringByValue().length(); }",
2063 materializeTemporaryExpr()));
2064
2065 EXPECT_TRUE(
2066 notMatches(ClassString +
2067 "string GetStringByValue();"
2068 "void run() { GetStringByValue(); }",
2069 materializeTemporaryExpr()));
2070}
2071
Manuel Klimek04616e42012-07-06 05:48:52 +00002072TEST(ConstructorDeclaration, SimpleCase) {
2073 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002074 cxxConstructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002075 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002076 cxxConstructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002077}
2078
2079TEST(ConstructorDeclaration, IsImplicit) {
2080 // This one doesn't match because the constructor is not added by the
2081 // compiler (it is not needed).
2082 EXPECT_TRUE(notMatches("class Foo { };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002083 cxxConstructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002084 // The compiler added the implicit default constructor.
2085 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Aaron Ballman512fb642015-09-17 13:30:52 +00002086 cxxConstructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002087 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002088 cxxConstructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00002089 // The compiler added an implicit assignment operator.
2090 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002091 cxxMethodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002092}
2093
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002094TEST(ConstructorDeclaration, IsExplicit) {
2095 EXPECT_TRUE(matches("struct S { explicit S(int); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002096 cxxConstructorDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002097 EXPECT_TRUE(notMatches("struct S { S(int); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002098 cxxConstructorDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002099}
2100
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002101TEST(ConstructorDeclaration, Kinds) {
2102 EXPECT_TRUE(matches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002103 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002104 EXPECT_TRUE(notMatches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002105 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002106 EXPECT_TRUE(notMatches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002107 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002108
2109 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002110 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002111 EXPECT_TRUE(matches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002112 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002113 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002114 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002115
2116 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002117 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002118 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002119 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002120 EXPECT_TRUE(matches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002121 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002122}
2123
Daniel Jasper1dad1832012-07-10 20:20:19 +00002124TEST(DestructorDeclaration, MatchesVirtualDestructor) {
2125 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002126 cxxDestructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002127}
2128
2129TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002130 EXPECT_TRUE(notMatches("class Foo {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00002131 cxxDestructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002132}
2133
Manuel Klimek04616e42012-07-06 05:48:52 +00002134TEST(HasAnyConstructorInitializer, SimpleCase) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002135 EXPECT_TRUE(
2136 notMatches("class Foo { Foo() { } };",
2137 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
2138 EXPECT_TRUE(
2139 matches("class Foo {"
2140 " Foo() : foo_() { }"
2141 " int foo_;"
2142 "};",
2143 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002144}
2145
2146TEST(HasAnyConstructorInitializer, ForField) {
2147 static const char Code[] =
2148 "class Baz { };"
2149 "class Foo {"
2150 " Foo() : foo_() { }"
2151 " Baz foo_;"
2152 " Baz bar_;"
2153 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002154 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002155 forField(hasType(recordDecl(hasName("Baz"))))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002156 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002157 forField(hasName("foo_"))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002158 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002159 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002160}
2161
2162TEST(HasAnyConstructorInitializer, WithInitializer) {
2163 static const char Code[] =
2164 "class Foo {"
2165 " Foo() : foo_(0) { }"
2166 " int foo_;"
2167 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002168 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002169 withInitializer(integerLiteral(equals(0)))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002170 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002171 withInitializer(integerLiteral(equals(1)))))));
2172}
2173
2174TEST(HasAnyConstructorInitializer, IsWritten) {
2175 static const char Code[] =
2176 "struct Bar { Bar(){} };"
2177 "class Foo {"
2178 " Foo() : foo_() { }"
2179 " Bar foo_;"
2180 " Bar bar_;"
2181 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002182 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002183 allOf(forField(hasName("foo_")), isWritten())))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002184 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002185 allOf(forField(hasName("bar_")), isWritten())))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002186 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002187 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2188}
2189
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002190TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
2191 static const char Code[] =
2192 "struct B {};"
2193 "struct D : B {"
2194 " int I;"
2195 " D(int i) : I(i) {}"
2196 "};"
2197 "struct E : B {"
2198 " E() : B() {}"
2199 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002200 EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002201 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2202 hasName("E")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002203 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002204 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2205 hasName("D")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002206 EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
Aaron Ballmaned455d42015-08-11 20:42:00 +00002207 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2208 hasName("D")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002209 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
Aaron Ballmaned455d42015-08-11 20:42:00 +00002210 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2211 hasName("E")))));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002212}
2213
Manuel Klimek04616e42012-07-06 05:48:52 +00002214TEST(Matcher, NewExpression) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002215 StatementMatcher New = cxxNewExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002216
2217 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2218 EXPECT_TRUE(
2219 matches("class X { public: X(); }; void x() { new X(); }", New));
2220 EXPECT_TRUE(
2221 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2222 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2223}
2224
2225TEST(Matcher, NewExpressionArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002226 StatementMatcher New = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002227 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002228
2229 EXPECT_TRUE(
2230 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2231 New));
2232 EXPECT_TRUE(
2233 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2234 New));
2235 EXPECT_TRUE(
2236 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2237 New));
2238
Aaron Ballman512fb642015-09-17 13:30:52 +00002239 StatementMatcher WrongIndex = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002240 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002241 EXPECT_TRUE(
2242 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2243 WrongIndex));
2244}
2245
2246TEST(Matcher, NewExpressionArgumentCount) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002247 StatementMatcher New = cxxConstructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002248
2249 EXPECT_TRUE(
2250 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2251 EXPECT_TRUE(
2252 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2253 New));
2254}
2255
Daniel Jasper1dad1832012-07-10 20:20:19 +00002256TEST(Matcher, DeleteExpression) {
2257 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002258 cxxDeleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002259}
2260
Manuel Klimek04616e42012-07-06 05:48:52 +00002261TEST(Matcher, DefaultArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002262 StatementMatcher Arg = cxxDefaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002263
2264 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2265 EXPECT_TRUE(
2266 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2267 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2268}
2269
2270TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002271 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002272 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2273 // wide string
2274 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2275 // with escaped characters
2276 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2277 // no matching -- though the data type is the same, there is no string literal
2278 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2279}
2280
2281TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002282 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002283 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2284 // wide character
2285 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2286 // wide character, Hex encoded, NOT MATCHED!
2287 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2288 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2289}
2290
2291TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002292 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002293 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2294 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2295 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2296 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2297
2298 // Non-matching cases (character literals, float and double)
2299 EXPECT_TRUE(notMatches("int i = L'a';",
2300 HasIntLiteral)); // this is actually a character
2301 // literal cast to int
2302 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2303 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2304 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2305}
2306
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002307TEST(Matcher, FloatLiterals) {
2308 StatementMatcher HasFloatLiteral = floatLiteral();
2309 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2310 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2311 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2312 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2313 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002314 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2315 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2316 EXPECT_TRUE(
2317 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002318
2319 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002320 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2321 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2322 EXPECT_TRUE(
2323 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002324}
2325
Daniel Jasper5901e472012-10-01 13:40:41 +00002326TEST(Matcher, NullPtrLiteral) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002327 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
Daniel Jasper5901e472012-10-01 13:40:41 +00002328}
2329
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002330TEST(Matcher, GNUNullExpr) {
2331 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2332}
2333
Daniel Jasper87c3d362012-09-20 14:12:57 +00002334TEST(Matcher, AsmStatement) {
2335 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2336}
2337
Manuel Klimek04616e42012-07-06 05:48:52 +00002338TEST(Matcher, Conditions) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002339 StatementMatcher Condition =
2340 ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002341
2342 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2343 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2344 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2345 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2346 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2347}
2348
Manuel Klimek909b5c942014-05-27 10:04:12 +00002349TEST(IfStmt, ChildTraversalMatchers) {
2350 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002351 ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002352 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002353 ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002354 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002355 ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002356 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002357 ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002358}
2359
Manuel Klimek04616e42012-07-06 05:48:52 +00002360TEST(MatchBinaryOperator, HasOperatorName) {
2361 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2362
2363 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2364 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2365}
2366
2367TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2368 StatementMatcher OperatorTrueFalse =
Aaron Ballman512fb642015-09-17 13:30:52 +00002369 binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
2370 hasRHS(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002371
2372 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2373 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2374 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
Alexander Kornienkoe39993e2015-11-02 22:23:21 +00002375
2376 StatementMatcher OperatorIntPointer = arraySubscriptExpr(
2377 hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
2378 EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
2379 EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
Manuel Klimek04616e42012-07-06 05:48:52 +00002380}
2381
2382TEST(MatchBinaryOperator, HasEitherOperand) {
2383 StatementMatcher HasOperand =
Aaron Ballman512fb642015-09-17 13:30:52 +00002384 binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002385
2386 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2387 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2388 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2389}
2390
2391TEST(Matcher, BinaryOperatorTypes) {
2392 // Integration test that verifies the AST provides all binary operators in
2393 // a way we expect.
2394 // FIXME: Operator ','
2395 EXPECT_TRUE(
2396 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2397 EXPECT_TRUE(
2398 matches("bool b; bool c = (b = true);",
2399 binaryOperator(hasOperatorName("="))));
2400 EXPECT_TRUE(
2401 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2402 EXPECT_TRUE(
2403 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2404 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2405 EXPECT_TRUE(
2406 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2407 EXPECT_TRUE(
2408 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2409 EXPECT_TRUE(
2410 matches("int i = 1; int j = (i <<= 2);",
2411 binaryOperator(hasOperatorName("<<="))));
2412 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2413 EXPECT_TRUE(
2414 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2415 EXPECT_TRUE(
2416 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2417 EXPECT_TRUE(
2418 matches("int i = 1; int j = (i >>= 2);",
2419 binaryOperator(hasOperatorName(">>="))));
2420 EXPECT_TRUE(
2421 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2422 EXPECT_TRUE(
2423 matches("int i = 42; int j = (i ^= 42);",
2424 binaryOperator(hasOperatorName("^="))));
2425 EXPECT_TRUE(
2426 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2427 EXPECT_TRUE(
2428 matches("int i = 42; int j = (i %= 42);",
2429 binaryOperator(hasOperatorName("%="))));
2430 EXPECT_TRUE(
2431 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2432 EXPECT_TRUE(
2433 matches("bool b = true && false;",
2434 binaryOperator(hasOperatorName("&&"))));
2435 EXPECT_TRUE(
2436 matches("bool b = true; bool c = (b &= false);",
2437 binaryOperator(hasOperatorName("&="))));
2438 EXPECT_TRUE(
2439 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2440 EXPECT_TRUE(
2441 matches("bool b = true || false;",
2442 binaryOperator(hasOperatorName("||"))));
2443 EXPECT_TRUE(
2444 matches("bool b = true; bool c = (b |= false);",
2445 binaryOperator(hasOperatorName("|="))));
2446 EXPECT_TRUE(
2447 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2448 EXPECT_TRUE(
2449 matches("int i = 42; int j = (i *= 23);",
2450 binaryOperator(hasOperatorName("*="))));
2451 EXPECT_TRUE(
2452 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2453 EXPECT_TRUE(
2454 matches("int i = 42; int j = (i /= 23);",
2455 binaryOperator(hasOperatorName("/="))));
2456 EXPECT_TRUE(
2457 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2458 EXPECT_TRUE(
2459 matches("int i = 42; int j = (i += 23);",
2460 binaryOperator(hasOperatorName("+="))));
2461 EXPECT_TRUE(
2462 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2463 EXPECT_TRUE(
2464 matches("int i = 42; int j = (i -= 23);",
2465 binaryOperator(hasOperatorName("-="))));
2466 EXPECT_TRUE(
2467 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2468 binaryOperator(hasOperatorName("->*"))));
2469 EXPECT_TRUE(
2470 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2471 binaryOperator(hasOperatorName(".*"))));
2472
2473 // Member expressions as operators are not supported in matches.
2474 EXPECT_TRUE(
2475 notMatches("struct A { void x(A *a) { a->x(this); } };",
2476 binaryOperator(hasOperatorName("->"))));
2477
2478 // Initializer assignments are not represented as operator equals.
2479 EXPECT_TRUE(
2480 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2481
2482 // Array indexing is not represented as operator.
2483 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2484
2485 // Overloaded operators do not match at all.
2486 EXPECT_TRUE(notMatches(
2487 "struct A { bool operator&&(const A &a) const { return false; } };"
2488 "void x() { A a, b; a && b; }",
2489 binaryOperator()));
2490}
2491
2492TEST(MatchUnaryOperator, HasOperatorName) {
2493 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2494
2495 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2496 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2497}
2498
2499TEST(MatchUnaryOperator, HasUnaryOperand) {
2500 StatementMatcher OperatorOnFalse =
Aaron Ballman512fb642015-09-17 13:30:52 +00002501 unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002502
2503 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2504 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2505}
2506
2507TEST(Matcher, UnaryOperatorTypes) {
2508 // Integration test that verifies the AST provides all unary operators in
2509 // a way we expect.
2510 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2511 EXPECT_TRUE(
2512 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2513 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2514 EXPECT_TRUE(
2515 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2516 EXPECT_TRUE(
2517 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2518 EXPECT_TRUE(
2519 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2520 EXPECT_TRUE(
2521 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2522 EXPECT_TRUE(
2523 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2524 EXPECT_TRUE(
2525 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2526 EXPECT_TRUE(
2527 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2528
2529 // We don't match conversion operators.
2530 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2531
2532 // Function calls are not represented as operator.
2533 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2534
2535 // Overloaded operators do not match at all.
2536 // FIXME: We probably want to add that.
2537 EXPECT_TRUE(notMatches(
2538 "struct A { bool operator!() const { return false; } };"
2539 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2540}
2541
2542TEST(Matcher, ConditionalOperator) {
2543 StatementMatcher Conditional = conditionalOperator(
Aaron Ballman512fb642015-09-17 13:30:52 +00002544 hasCondition(cxxBoolLiteral(equals(true))),
2545 hasTrueExpression(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002546
2547 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2548 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2549 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2550
2551 StatementMatcher ConditionalFalse = conditionalOperator(
Aaron Ballman512fb642015-09-17 13:30:52 +00002552 hasFalseExpression(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002553
2554 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2555 EXPECT_TRUE(
2556 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2557}
2558
Daniel Jasper1dad1832012-07-10 20:20:19 +00002559TEST(ArraySubscriptMatchers, ArraySubscripts) {
2560 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2561 arraySubscriptExpr()));
2562 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2563 arraySubscriptExpr()));
2564}
2565
2566TEST(ArraySubscriptMatchers, ArrayIndex) {
2567 EXPECT_TRUE(matches(
2568 "int i[2]; void f() { i[1] = 1; }",
2569 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2570 EXPECT_TRUE(matches(
2571 "int i[2]; void f() { 1[i] = 1; }",
2572 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2573 EXPECT_TRUE(notMatches(
2574 "int i[2]; void f() { i[1] = 1; }",
2575 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2576}
2577
2578TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2579 EXPECT_TRUE(matches(
2580 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002581 arraySubscriptExpr(hasBase(implicitCastExpr(
2582 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002583}
2584
Manuel Klimek04616e42012-07-06 05:48:52 +00002585TEST(Matcher, HasNameSupportsNamespaces) {
2586 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002587 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002588 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002589 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002590 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002591 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002592 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002593 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002594 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002595 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002596 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002597 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002598 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002599 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002600 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002601 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002602 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002603 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002604 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002605 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002606 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002607 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002608 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002609 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002610}
2611
2612TEST(Matcher, HasNameSupportsOuterClasses) {
2613 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002614 matches("class A { class B { class C; }; };",
2615 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002616 EXPECT_TRUE(
2617 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002618 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002619 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002620 matches("class A { class B { class C; }; };",
2621 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002622 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002623 matches("class A { class B { class C; }; };",
2624 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002625 EXPECT_TRUE(
2626 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002627 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002628 EXPECT_TRUE(
2629 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002630 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002631 EXPECT_TRUE(
2632 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002633 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002634 EXPECT_TRUE(
2635 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002636 recordDecl(hasName("::C"))));
2637 EXPECT_TRUE(
2638 notMatches("class A { class B { class C; }; };",
2639 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002640 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002641 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002642 EXPECT_TRUE(
2643 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002644 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002645}
2646
2647TEST(Matcher, IsDefinition) {
2648 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002649 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002650 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2651 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2652
2653 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002654 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002655 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2656 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2657
2658 DeclarationMatcher DefinitionOfMethodA =
Aaron Ballman512fb642015-09-17 13:30:52 +00002659 cxxMethodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002660 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2661 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2662}
2663
2664TEST(Matcher, OfClass) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002665 StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002666 ofClass(hasName("X")))));
2667
2668 EXPECT_TRUE(
2669 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2670 EXPECT_TRUE(
2671 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2672 Constructor));
2673 EXPECT_TRUE(
2674 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2675 Constructor));
2676}
2677
2678TEST(Matcher, VisitsTemplateInstantiations) {
2679 EXPECT_TRUE(matches(
2680 "class A { public: void x(); };"
2681 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002682 "void f() { B<A> b; b.y(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002683 callExpr(callee(cxxMethodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002684
2685 EXPECT_TRUE(matches(
2686 "class A { public: void x(); };"
2687 "class C {"
2688 " public:"
2689 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2690 "};"
2691 "void f() {"
2692 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002693 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00002694 recordDecl(hasName("C"), hasDescendant(callExpr(
2695 callee(cxxMethodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002696}
2697
Daniel Jasper1dad1832012-07-10 20:20:19 +00002698TEST(Matcher, HandlesNullQualTypes) {
2699 // FIXME: Add a Type matcher so we can replace uses of this
2700 // variable with Type(True())
2701 const TypeMatcher AnyType = anything();
2702
2703 // We don't really care whether this matcher succeeds; we're testing that
2704 // it completes without crashing.
2705 EXPECT_TRUE(matches(
2706 "struct A { };"
2707 "template <typename T>"
2708 "void f(T t) {"
2709 " T local_t(t /* this becomes a null QualType in the AST */);"
2710 "}"
2711 "void g() {"
2712 " f(0);"
2713 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002714 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002715 anyOf(
2716 TypeMatcher(hasDeclaration(anything())),
2717 pointsTo(AnyType),
2718 references(AnyType)
2719 // Other QualType matchers should go here.
2720 ))))));
2721}
2722
Manuel Klimek04616e42012-07-06 05:48:52 +00002723// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002724AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002725 // Make sure all special variables are used: node, match_finder,
2726 // bound_nodes_builder, and the parameter named 'AMatcher'.
2727 return AMatcher.matches(Node, Finder, Builder);
2728}
2729
2730TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002731 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002732
2733 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002734 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002735
2736 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002737 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002738
2739 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002740 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002741}
2742
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002743AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2744 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2745 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002746 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002747 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002748 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2749 ASTMatchFinder::BK_First);
2750}
2751
2752TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002753 DeclarationMatcher HasClassB =
2754 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002755
2756 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002757 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002758
2759 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002760 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002761
2762 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002763 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002764
2765 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002766 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002767
2768 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2769}
2770
2771TEST(For, FindsForLoops) {
2772 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2773 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002774 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2775 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002776 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002777}
2778
Daniel Jasper4e566c42012-07-12 08:50:38 +00002779TEST(For, ForLoopInternals) {
2780 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2781 forStmt(hasCondition(anything()))));
2782 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2783 forStmt(hasLoopInit(anything()))));
2784}
2785
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002786TEST(For, ForRangeLoopInternals) {
2787 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002788 cxxForRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002789 EXPECT_TRUE(matches(
2790 "void f(){ int a[] {1, 2}; for (int i : a); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002791 cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002792}
2793
Daniel Jasper4e566c42012-07-12 08:50:38 +00002794TEST(For, NegativeForLoopInternals) {
2795 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002796 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002797 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2798 forStmt(hasLoopInit(anything()))));
2799}
2800
Manuel Klimek04616e42012-07-06 05:48:52 +00002801TEST(For, ReportsNoFalsePositives) {
2802 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2803 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2804}
2805
2806TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002807 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2808 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2809 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002810}
2811
2812TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2813 // It's not a compound statement just because there's "{}" in the source
2814 // text. This is an AST search, not grep.
2815 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002816 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002817 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002818 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002819}
2820
Daniel Jasper4e566c42012-07-12 08:50:38 +00002821TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002822 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002823 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002824 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002825 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002826 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002827 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002828 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002829 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002830 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002831 cxxForRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002832}
2833
2834TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2835 // The simplest case: every compound statement is in a function
2836 // definition, and the function body itself must be a compound
2837 // statement.
2838 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002839 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002840}
2841
2842TEST(HasAnySubstatement, IsNotRecursive) {
2843 // It's really "has any immediate substatement".
2844 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002845 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002846}
2847
2848TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2849 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002850 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002851}
2852
2853TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2854 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002855 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002856}
2857
2858TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2859 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002860 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002861 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002862 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002863}
2864
2865TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2866 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002867 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002868 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002869 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002870 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002871 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002872}
2873
2874TEST(StatementCountIs, WorksWithMultipleStatements) {
2875 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002876 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002877}
2878
2879TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2880 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002881 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002882 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002883 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002884 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002885 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002886 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002887 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002888}
2889
2890TEST(Member, WorksInSimplestCase) {
2891 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002892 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002893}
2894
2895TEST(Member, DoesNotMatchTheBaseExpression) {
2896 // Don't pick out the wrong part of the member expression, this should
2897 // be checking the member (name) only.
2898 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002899 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002900}
2901
2902TEST(Member, MatchesInMemberFunctionCall) {
2903 EXPECT_TRUE(matches("void f() {"
2904 " struct { void first() {}; } s;"
2905 " s.first();"
2906 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002907 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002908}
2909
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002910TEST(Member, MatchesMember) {
2911 EXPECT_TRUE(matches(
2912 "struct A { int i; }; void f() { A a; a.i = 2; }",
2913 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2914 EXPECT_TRUE(notMatches(
2915 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2916 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2917}
2918
Daniel Jasper639522c2013-02-25 12:02:08 +00002919TEST(Member, UnderstandsAccess) {
2920 EXPECT_TRUE(matches(
2921 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2922 EXPECT_TRUE(notMatches(
2923 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2924 EXPECT_TRUE(notMatches(
2925 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2926
2927 EXPECT_TRUE(notMatches(
2928 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2929 EXPECT_TRUE(notMatches(
2930 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2931 EXPECT_TRUE(matches(
2932 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2933
2934 EXPECT_TRUE(notMatches(
2935 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2936 EXPECT_TRUE(matches("class A { protected: int i; };",
2937 fieldDecl(isProtected(), hasName("i"))));
2938 EXPECT_TRUE(notMatches(
2939 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2940
2941 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2942 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2943 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2944 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2945}
2946
Dmitri Gribenko06963042012-08-18 00:29:27 +00002947TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002948 // Fails in C++11 mode
2949 EXPECT_TRUE(matchesConditionally(
2950 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2951 "class X { void *operator new(std::size_t); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002952 cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002953
2954 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002955 cxxMethodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002956
Daniel Jasper5901e472012-10-01 13:40:41 +00002957 // Fails in C++11 mode
2958 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002959 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2960 "class X { void operator delete[](void*, std::size_t); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002961 cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002962}
2963
Manuel Klimek04616e42012-07-06 05:48:52 +00002964TEST(HasObjectExpression, DoesNotMatchMember) {
2965 EXPECT_TRUE(notMatches(
2966 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002967 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002968}
2969
2970TEST(HasObjectExpression, MatchesBaseOfVariable) {
2971 EXPECT_TRUE(matches(
2972 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002973 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002974 EXPECT_TRUE(matches(
2975 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002976 memberExpr(hasObjectExpression(
2977 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002978}
2979
2980TEST(HasObjectExpression,
2981 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2982 EXPECT_TRUE(matches(
2983 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002984 memberExpr(hasObjectExpression(
2985 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002986 EXPECT_TRUE(matches(
2987 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002988 memberExpr(hasObjectExpression(
2989 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002990}
2991
2992TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002993 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2994 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2995 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2996 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002997}
2998
2999TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003000 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003001}
3002
3003TEST(IsConstQualified, MatchesConstInt) {
3004 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003005 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003006}
3007
3008TEST(IsConstQualified, MatchesConstPointer) {
3009 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003010 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003011}
3012
3013TEST(IsConstQualified, MatchesThroughTypedef) {
3014 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003015 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003016 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003017 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003018}
3019
3020TEST(IsConstQualified, DoesNotMatchInappropriately) {
3021 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003022 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003023 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003024 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003025}
3026
Sam Panzer80c13772012-08-16 16:58:10 +00003027TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003028 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
3029 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
3030 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
3031 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003032}
3033TEST(CastExpression, MatchesImplicitCasts) {
3034 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00003035 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003036 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00003037 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003038}
3039
3040TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003041 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
3042 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
3043 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
3044 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003045}
3046
Manuel Klimek04616e42012-07-06 05:48:52 +00003047TEST(ReinterpretCast, MatchesSimpleCase) {
3048 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003049 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003050}
3051
3052TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003053 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003054 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003055 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003056 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003057 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003058 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3059 "B b;"
3060 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003061 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003062}
3063
3064TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003065 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003066 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003067 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003068}
3069
3070TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003071 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003072 EXPECT_TRUE(
3073 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003074 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003075 EXPECT_TRUE(
3076 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003077 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003078}
3079
3080TEST(DynamicCast, MatchesSimpleCase) {
3081 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
3082 "B b;"
3083 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003084 cxxDynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003085}
3086
3087TEST(StaticCast, MatchesSimpleCase) {
3088 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Aaron Ballman512fb642015-09-17 13:30:52 +00003089 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003090}
3091
3092TEST(StaticCast, DoesNotMatchOtherCasts) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003093 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003094 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003095 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003096 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003097 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003098 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3099 "B b;"
3100 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003101 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003102}
3103
Daniel Jasper417f7762012-09-18 13:36:17 +00003104TEST(CStyleCast, MatchesSimpleCase) {
3105 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
3106}
3107
3108TEST(CStyleCast, DoesNotMatchOtherCasts) {
3109 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
3110 "char q, *r = const_cast<char*>(&q);"
3111 "void* s = reinterpret_cast<char*>(&s);"
3112 "struct B { virtual ~B() {} }; struct D : B {};"
3113 "B b;"
3114 "D* t = dynamic_cast<D*>(&b);",
3115 cStyleCastExpr()));
3116}
3117
Manuel Klimek04616e42012-07-06 05:48:52 +00003118TEST(HasDestinationType, MatchesSimpleCase) {
3119 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003120 cxxStaticCastExpr(hasDestinationType(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003121 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003122}
3123
Sam Panzer80c13772012-08-16 16:58:10 +00003124TEST(HasImplicitDestinationType, MatchesSimpleCase) {
3125 // This test creates an implicit const cast.
3126 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003127 implicitCastExpr(
3128 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003129 // This test creates an implicit array-to-pointer cast.
3130 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003131 implicitCastExpr(hasImplicitDestinationType(
3132 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003133}
3134
3135TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
3136 // This test creates an implicit cast from int to char.
3137 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003138 implicitCastExpr(hasImplicitDestinationType(
3139 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003140 // This test creates an implicit array-to-pointer cast.
3141 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003142 implicitCastExpr(hasImplicitDestinationType(
3143 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003144}
3145
3146TEST(ImplicitCast, MatchesSimpleCase) {
3147 // This test creates an implicit const cast.
3148 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003149 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003150 // This test creates an implicit cast from int to char.
3151 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003152 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003153 // This test creates an implicit array-to-pointer cast.
3154 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003155 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003156}
3157
3158TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003159 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00003160 // are present, and that it ignores explicit and paren casts.
3161
3162 // These two test cases have no casts.
3163 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003164 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003165 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003166 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003167
3168 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003169 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003170 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003171 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003172
3173 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003174 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003175}
3176
3177TEST(IgnoringImpCasts, MatchesImpCasts) {
3178 // This test checks that ignoringImpCasts matches when implicit casts are
3179 // present and its inner matcher alone does not match.
3180 // Note that this test creates an implicit const cast.
3181 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003182 varDecl(hasInitializer(ignoringImpCasts(
3183 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003184 // This test creates an implict cast from int to char.
3185 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003186 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003187 integerLiteral(equals(0)))))));
3188}
3189
3190TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3191 // These tests verify that ignoringImpCasts does not match if the inner
3192 // matcher does not match.
3193 // Note that the first test creates an implicit const cast.
3194 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003195 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003196 unless(anything()))))));
3197 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003198 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003199 unless(anything()))))));
3200
3201 // These tests verify that ignoringImplictCasts does not look through explicit
3202 // casts or parentheses.
3203 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003204 varDecl(hasInitializer(ignoringImpCasts(
3205 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003206 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003207 varDecl(hasInitializer(ignoringImpCasts(
3208 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003209 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003210 varDecl(hasInitializer(ignoringImpCasts(
3211 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003212 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003213 varDecl(hasInitializer(ignoringImpCasts(
3214 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003215}
3216
3217TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3218 // This test verifies that expressions that do not have implicit casts
3219 // still match the inner matcher.
3220 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003221 varDecl(hasInitializer(ignoringImpCasts(
3222 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003223}
3224
3225TEST(IgnoringParenCasts, MatchesParenCasts) {
3226 // This test checks that ignoringParenCasts matches when parentheses and/or
3227 // casts are present and its inner matcher alone does not match.
3228 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003229 varDecl(hasInitializer(ignoringParenCasts(
3230 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003231 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003232 varDecl(hasInitializer(ignoringParenCasts(
3233 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003234
3235 // This test creates an implict cast from int to char in addition to the
3236 // parentheses.
3237 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003238 varDecl(hasInitializer(ignoringParenCasts(
3239 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003240
3241 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003242 varDecl(hasInitializer(ignoringParenCasts(
3243 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003244 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003245 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003246 integerLiteral(equals(0)))))));
3247}
3248
3249TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3250 // This test verifies that expressions that do not have any casts still match.
3251 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003252 varDecl(hasInitializer(ignoringParenCasts(
3253 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003254}
3255
3256TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3257 // These tests verify that ignoringImpCasts does not match if the inner
3258 // matcher does not match.
3259 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003260 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003261 unless(anything()))))));
3262
3263 // This test creates an implicit cast from int to char in addition to the
3264 // parentheses.
3265 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003266 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003267 unless(anything()))))));
3268
3269 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003270 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003271 unless(anything()))))));
3272}
3273
3274TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3275 // This test checks that ignoringParenAndImpCasts matches when
3276 // parentheses and/or implicit casts are present and its inner matcher alone
3277 // does not match.
3278 // Note that this test creates an implicit const cast.
3279 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003280 varDecl(hasInitializer(ignoringParenImpCasts(
3281 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003282 // This test creates an implicit cast from int to char.
3283 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003284 varDecl(hasInitializer(ignoringParenImpCasts(
3285 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003286}
3287
3288TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3289 // This test verifies that expressions that do not have parentheses or
3290 // implicit casts still match.
3291 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003292 varDecl(hasInitializer(ignoringParenImpCasts(
3293 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003294 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003295 varDecl(hasInitializer(ignoringParenImpCasts(
3296 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003297}
3298
3299TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3300 // These tests verify that ignoringParenImpCasts does not match if
3301 // the inner matcher does not match.
3302 // This test creates an implicit cast.
3303 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003304 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003305 unless(anything()))))));
3306 // These tests verify that ignoringParenAndImplictCasts does not look
3307 // through explicit casts.
3308 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003309 varDecl(hasInitializer(ignoringParenImpCasts(
3310 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003311 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003312 varDecl(hasInitializer(ignoringParenImpCasts(
3313 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003314 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003315 varDecl(hasInitializer(ignoringParenImpCasts(
3316 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003317}
3318
Manuel Klimeke9235692012-07-25 10:02:02 +00003319TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003320 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3321 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003322 implicitCastExpr(
Aaron Ballman512fb642015-09-17 13:30:52 +00003323 hasSourceExpression(cxxConstructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003324}
3325
Manuel Klimeke9235692012-07-25 10:02:02 +00003326TEST(HasSourceExpression, MatchesExplicitCasts) {
3327 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003328 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003329 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003330 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003331}
3332
Manuel Klimek04616e42012-07-06 05:48:52 +00003333TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003334 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003335}
3336
3337TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003338 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003339}
3340
3341TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003342 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003343}
3344
3345TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003346 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003347}
3348
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003349TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3350 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3351 "const Foo f = Foo();",
3352 varDecl(hasInitializer(exprWithCleanups()))));
3353 EXPECT_FALSE(matches("struct Foo { };"
3354 "const Foo f = Foo();",
3355 varDecl(hasInitializer(exprWithCleanups()))));
3356}
3357
Daniel Jasper1dad1832012-07-10 20:20:19 +00003358TEST(InitListExpression, MatchesInitListExpression) {
3359 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3360 initListExpr(hasType(asString("int [2]")))));
3361 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003362 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003363 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3364 "void f();"
3365 "S s[1] = { &f };",
3366 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003367 EXPECT_TRUE(
3368 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003369}
3370
3371TEST(UsingDeclaration, MatchesUsingDeclarations) {
3372 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3373 usingDecl()));
3374}
3375
3376TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3377 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3378 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3379}
3380
3381TEST(UsingDeclaration, MatchesSpecificTarget) {
3382 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3383 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003384 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003385 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3386 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003387 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003388}
3389
3390TEST(UsingDeclaration, ThroughUsingDeclaration) {
3391 EXPECT_TRUE(matches(
3392 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003393 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003394 EXPECT_TRUE(notMatches(
3395 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003396 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003397}
3398
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003399TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3400 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3401 usingDirectiveDecl()));
3402 EXPECT_FALSE(
3403 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3404}
3405
Sam Panzerd624bfb2012-08-16 17:20:59 +00003406TEST(SingleDecl, IsSingleDecl) {
3407 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003408 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003409 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3410 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3411 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3412 SingleDeclStmt));
3413}
3414
3415TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003416 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003417
3418 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003419 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003420 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003421 declStmt(containsDeclaration(0, MatchesInit),
3422 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003423 unsigned WrongIndex = 42;
3424 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003425 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003426 MatchesInit))));
3427}
3428
3429TEST(DeclCount, DeclCountIsCorrect) {
3430 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003431 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003432 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003433 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003434 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003435 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003436}
3437
Manuel Klimek04616e42012-07-06 05:48:52 +00003438TEST(While, MatchesWhileLoops) {
3439 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3440 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3441 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3442}
3443
3444TEST(Do, MatchesDoLoops) {
3445 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3446 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3447}
3448
3449TEST(Do, DoesNotMatchWhileLoops) {
3450 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3451}
3452
3453TEST(SwitchCase, MatchesCase) {
3454 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3455 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3456 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3457 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3458}
3459
Daniel Jasper87c3d362012-09-20 14:12:57 +00003460TEST(SwitchCase, MatchesSwitch) {
3461 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3462 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3463 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3464 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3465}
3466
Peter Collingbourne3154a102013-05-10 11:52:02 +00003467TEST(SwitchCase, MatchesEachCase) {
3468 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3469 switchStmt(forEachSwitchCase(caseStmt()))));
3470 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3471 switchStmt(forEachSwitchCase(caseStmt()))));
3472 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3473 switchStmt(forEachSwitchCase(caseStmt()))));
3474 EXPECT_TRUE(notMatches(
3475 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3476 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3477 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3478 switchStmt(forEachSwitchCase(
3479 caseStmt(hasCaseConstant(integerLiteral()))))));
3480 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3481 switchStmt(forEachSwitchCase(
3482 caseStmt(hasCaseConstant(integerLiteral()))))));
3483 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3484 switchStmt(forEachSwitchCase(
3485 caseStmt(hasCaseConstant(integerLiteral()))))));
3486 EXPECT_TRUE(matchAndVerifyResultTrue(
3487 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3488 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3489 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3490}
3491
Manuel Klimekba46fc02013-07-19 11:50:54 +00003492TEST(ForEachConstructorInitializer, MatchesInitializers) {
3493 EXPECT_TRUE(matches(
3494 "struct X { X() : i(42), j(42) {} int i, j; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003495 cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer()))));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003496}
3497
Daniel Jasper87c3d362012-09-20 14:12:57 +00003498TEST(ExceptionHandling, SimpleCases) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003499 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
3500 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
3501 EXPECT_TRUE(
3502 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003503 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003504 cxxThrowExpr()));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003505 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003506 cxxThrowExpr()));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003507 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003508 cxxCatchStmt(isCatchAll())));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003509 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003510 cxxCatchStmt(isCatchAll())));
Aaron Ballman39918462015-07-15 17:11:21 +00003511 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3512 varDecl(isExceptionVariable())));
3513 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3514 varDecl(isExceptionVariable())));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003515}
3516
Manuel Klimek04616e42012-07-06 05:48:52 +00003517TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3518 EXPECT_TRUE(notMatches(
3519 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003520 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003521 EXPECT_TRUE(notMatches(
3522 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003523 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003524}
3525
3526TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3527 EXPECT_TRUE(matches(
3528 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003529 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003530}
3531
3532TEST(ForEach, BindsOneNode) {
3533 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003534 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003535 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003536}
3537
3538TEST(ForEach, BindsMultipleNodes) {
3539 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003540 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003541 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003542}
3543
3544TEST(ForEach, BindsRecursiveCombinations) {
3545 EXPECT_TRUE(matchAndVerifyResultTrue(
3546 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003547 recordDecl(hasName("C"),
3548 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003549 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003550}
3551
3552TEST(ForEachDescendant, BindsOneNode) {
3553 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003554 recordDecl(hasName("C"),
3555 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003556 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003557}
3558
Daniel Jasper94a56852012-11-16 18:39:22 +00003559TEST(ForEachDescendant, NestedForEachDescendant) {
3560 DeclarationMatcher m = recordDecl(
3561 isDefinition(), decl().bind("x"), hasName("C"));
3562 EXPECT_TRUE(matchAndVerifyResultTrue(
3563 "class A { class B { class C {}; }; };",
3564 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3565 new VerifyIdIsBoundTo<Decl>("x", "C")));
3566
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003567 // Check that a partial match of 'm' that binds 'x' in the
3568 // first part of anyOf(m, anything()) will not overwrite the
3569 // binding created by the earlier binding in the hasDescendant.
3570 EXPECT_TRUE(matchAndVerifyResultTrue(
3571 "class A { class B { class C {}; }; };",
3572 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3573 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003574}
3575
Manuel Klimek04616e42012-07-06 05:48:52 +00003576TEST(ForEachDescendant, BindsMultipleNodes) {
3577 EXPECT_TRUE(matchAndVerifyResultTrue(
3578 "class C { class D { int x; int y; }; "
3579 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003580 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003581 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003582}
3583
3584TEST(ForEachDescendant, BindsRecursiveCombinations) {
3585 EXPECT_TRUE(matchAndVerifyResultTrue(
3586 "class C { class D { "
3587 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003588 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3589 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003590 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003591}
3592
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003593TEST(ForEachDescendant, BindsCombinations) {
3594 EXPECT_TRUE(matchAndVerifyResultTrue(
3595 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3596 "(true) {} }",
3597 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3598 forEachDescendant(whileStmt().bind("while"))),
3599 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3600}
3601
3602TEST(Has, DoesNotDeleteBindings) {
3603 EXPECT_TRUE(matchAndVerifyResultTrue(
3604 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3605 new VerifyIdIsBoundTo<Decl>("x", 1)));
3606}
3607
3608TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3609 // Those matchers cover all the cases where an inner matcher is called
3610 // and there is not a 1:1 relationship between the match of the outer
3611 // matcher and the match of the inner matcher.
3612 // The pattern to look for is:
3613 // ... return InnerMatcher.matches(...); ...
3614 // In which case no special handling is needed.
3615 //
3616 // On the other hand, if there are multiple alternative matches
3617 // (for example forEach*) or matches might be discarded (for example has*)
3618 // the implementation must make sure that the discarded matches do not
3619 // affect the bindings.
3620 // When new such matchers are added, add a test here that:
3621 // - matches a simple node, and binds it as the first thing in the matcher:
3622 // recordDecl(decl().bind("x"), hasName("X")))
3623 // - uses the matcher under test afterwards in a way that not the first
3624 // alternative is matched; for anyOf, that means the first branch
3625 // would need to return false; for hasAncestor, it means that not
3626 // the direct parent matches the inner matcher.
3627
3628 EXPECT_TRUE(matchAndVerifyResultTrue(
3629 "class X { int y; };",
3630 recordDecl(
3631 recordDecl().bind("x"), hasName("::X"),
3632 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3633 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3634 EXPECT_TRUE(matchAndVerifyResultTrue(
3635 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3636 anyOf(unless(anything()), anything())),
3637 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3638 EXPECT_TRUE(matchAndVerifyResultTrue(
3639 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3640 classTemplateSpecializationDecl(
3641 decl().bind("x"),
3642 hasAnyTemplateArgument(refersToType(asString("int")))),
3643 new VerifyIdIsBoundTo<Decl>("x", 1)));
3644 EXPECT_TRUE(matchAndVerifyResultTrue(
3645 "class X { void f(); void g(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003646 cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003647 new VerifyIdIsBoundTo<Decl>("x", 1)));
3648 EXPECT_TRUE(matchAndVerifyResultTrue(
3649 "class X { X() : a(1), b(2) {} double a; int b; };",
3650 recordDecl(decl().bind("x"),
Aaron Ballman512fb642015-09-17 13:30:52 +00003651 has(cxxConstructorDecl(
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003652 hasAnyConstructorInitializer(forField(hasName("b")))))),
3653 new VerifyIdIsBoundTo<Decl>("x", 1)));
3654 EXPECT_TRUE(matchAndVerifyResultTrue(
3655 "void x(int, int) { x(0, 42); }",
3656 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3657 new VerifyIdIsBoundTo<Expr>("x", 1)));
3658 EXPECT_TRUE(matchAndVerifyResultTrue(
3659 "void x(int, int y) {}",
3660 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3661 new VerifyIdIsBoundTo<Decl>("x", 1)));
3662 EXPECT_TRUE(matchAndVerifyResultTrue(
3663 "void x() { return; if (true) {} }",
3664 functionDecl(decl().bind("x"),
3665 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3666 new VerifyIdIsBoundTo<Decl>("x", 1)));
3667 EXPECT_TRUE(matchAndVerifyResultTrue(
3668 "namespace X { void b(int); void b(); }"
3669 "using X::b;",
3670 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3671 functionDecl(parameterCountIs(1))))),
3672 new VerifyIdIsBoundTo<Decl>("x", 1)));
3673 EXPECT_TRUE(matchAndVerifyResultTrue(
3674 "class A{}; class B{}; class C : B, A {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003675 cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003676 new VerifyIdIsBoundTo<Decl>("x", 1)));
3677 EXPECT_TRUE(matchAndVerifyResultTrue(
3678 "class A{}; typedef A B; typedef A C; typedef A D;"
3679 "class E : A {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003680 cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003681 new VerifyIdIsBoundTo<Decl>("x", 1)));
3682 EXPECT_TRUE(matchAndVerifyResultTrue(
3683 "class A { class B { void f() {} }; };",
3684 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3685 new VerifyIdIsBoundTo<Decl>("x", 1)));
3686 EXPECT_TRUE(matchAndVerifyResultTrue(
3687 "template <typename T> struct A { struct B {"
3688 " void f() { if(true) {} }"
3689 "}; };"
3690 "void t() { A<int>::B b; b.f(); }",
3691 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3692 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3693 EXPECT_TRUE(matchAndVerifyResultTrue(
3694 "class A {};",
3695 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3696 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003697 EXPECT_TRUE(matchAndVerifyResultTrue(
3698 "class A { A() : s(), i(42) {} const char *s; int i; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003699 cxxConstructorDecl(hasName("::A::A"), decl().bind("x"),
3700 forEachConstructorInitializer(forField(hasName("i")))),
Manuel Klimekba46fc02013-07-19 11:50:54 +00003701 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003702}
3703
Daniel Jasper33806cd2012-11-11 22:14:55 +00003704TEST(ForEachDescendant, BindsCorrectNodes) {
3705 EXPECT_TRUE(matchAndVerifyResultTrue(
3706 "class C { void f(); int i; };",
3707 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3708 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3709 EXPECT_TRUE(matchAndVerifyResultTrue(
3710 "class C { void f() {} int i; };",
3711 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3712 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3713}
3714
Manuel Klimekabf43712013-02-04 10:59:20 +00003715TEST(FindAll, BindsNodeOnMatch) {
3716 EXPECT_TRUE(matchAndVerifyResultTrue(
3717 "class A {};",
3718 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3719 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3720}
3721
3722TEST(FindAll, BindsDescendantNodeOnMatch) {
3723 EXPECT_TRUE(matchAndVerifyResultTrue(
3724 "class A { int a; int b; };",
3725 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3726 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3727}
3728
3729TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3730 EXPECT_TRUE(matchAndVerifyResultTrue(
3731 "class A { int a; int b; };",
3732 recordDecl(hasName("::A"),
3733 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3734 fieldDecl().bind("v"))))),
3735 new VerifyIdIsBoundTo<Decl>("v", 3)));
3736
3737 EXPECT_TRUE(matchAndVerifyResultTrue(
3738 "class A { class B {}; class C {}; };",
3739 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3740 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3741}
3742
Manuel Klimek88b95872013-02-04 09:42:38 +00003743TEST(EachOf, TriggersForEachMatch) {
3744 EXPECT_TRUE(matchAndVerifyResultTrue(
3745 "class A { int a; int b; };",
3746 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3747 has(fieldDecl(hasName("b")).bind("v")))),
3748 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3749}
3750
3751TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3752 EXPECT_TRUE(matchAndVerifyResultTrue(
3753 "class A { int a; int c; };",
3754 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3755 has(fieldDecl(hasName("b")).bind("v")))),
3756 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3757 EXPECT_TRUE(matchAndVerifyResultTrue(
3758 "class A { int c; int b; };",
3759 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3760 has(fieldDecl(hasName("b")).bind("v")))),
3761 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3762 EXPECT_TRUE(notMatches(
3763 "class A { int c; int d; };",
3764 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3765 has(fieldDecl(hasName("b")).bind("v"))))));
3766}
Manuel Klimek04616e42012-07-06 05:48:52 +00003767
3768TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3769 // Make sure that we can both match the class by name (::X) and by the type
3770 // the template was instantiated with (via a field).
3771
3772 EXPECT_TRUE(matches(
3773 "template <typename T> class X {}; class A {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003774 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003775
3776 EXPECT_TRUE(matches(
3777 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003778 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003779 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003780}
3781
3782TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3783 EXPECT_TRUE(matches(
3784 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003785 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003786 isTemplateInstantiation())));
3787}
3788
3789TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3790 EXPECT_TRUE(matches(
3791 "template <typename T> class X { T t; }; class A {};"
3792 "template class X<A>;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003793 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003794 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003795}
3796
3797TEST(IsTemplateInstantiation,
3798 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3799 EXPECT_TRUE(matches(
3800 "template <typename T> class X {};"
3801 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003802 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003803}
3804
3805TEST(IsTemplateInstantiation,
3806 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3807 EXPECT_TRUE(matches(
3808 "class A {};"
3809 "class X {"
3810 " template <typename U> class Y { U u; };"
3811 " Y<A> y;"
3812 "};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003813 cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003814}
3815
3816TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3817 // FIXME: Figure out whether this makes sense. It doesn't affect the
3818 // normal use case as long as the uppermost instantiation always is marked
3819 // as template instantiation, but it might be confusing as a predicate.
3820 EXPECT_TRUE(matches(
3821 "class A {};"
3822 "template <typename T> class X {"
3823 " template <typename U> class Y { U u; };"
3824 " Y<T> y;"
3825 "}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003826 cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003827}
3828
3829TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3830 EXPECT_TRUE(notMatches(
3831 "template <typename T> class X {}; class A {};"
3832 "template <> class X<A> {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003833 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003834}
3835
3836TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3837 EXPECT_TRUE(notMatches(
3838 "class A {}; class Y { A a; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003839 cxxRecordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003840}
3841
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003842TEST(IsInstantiated, MatchesInstantiation) {
3843 EXPECT_TRUE(
3844 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003845 cxxRecordDecl(isInstantiated())));
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003846}
3847
3848TEST(IsInstantiated, NotMatchesDefinition) {
3849 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003850 cxxRecordDecl(isInstantiated())));
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003851}
3852
3853TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3854 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3855 "class Y { A<int> a; }; Y y;",
3856 declStmt(isInTemplateInstantiation())));
3857}
3858
3859TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3860 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3861 declStmt(isInTemplateInstantiation())));
3862}
3863
3864TEST(IsInstantiated, MatchesFunctionInstantiation) {
3865 EXPECT_TRUE(
3866 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3867 functionDecl(isInstantiated())));
3868}
3869
3870TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3871 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3872 varDecl(isInstantiated())));
3873}
3874
3875TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3876 EXPECT_TRUE(
3877 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3878 declStmt(isInTemplateInstantiation())));
3879}
3880
3881TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3882 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3883 declStmt(isInTemplateInstantiation())));
3884}
3885
3886TEST(IsInTemplateInstantiation, Sharing) {
3887 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3888 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3889 // and makes the matcher behave in non-obvious ways.
3890 EXPECT_TRUE(notMatches(
3891 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3892 Matcher));
3893 EXPECT_TRUE(matches(
3894 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3895 Matcher));
3896}
3897
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003898TEST(IsExplicitTemplateSpecialization,
3899 DoesNotMatchPrimaryTemplate) {
3900 EXPECT_TRUE(notMatches(
3901 "template <typename T> class X {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003902 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003903 EXPECT_TRUE(notMatches(
3904 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003905 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003906}
3907
3908TEST(IsExplicitTemplateSpecialization,
3909 DoesNotMatchExplicitTemplateInstantiations) {
3910 EXPECT_TRUE(notMatches(
3911 "template <typename T> class X {};"
3912 "template class X<int>; extern template class X<long>;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003913 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003914 EXPECT_TRUE(notMatches(
3915 "template <typename T> void f(T t) {}"
3916 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003917 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003918}
3919
3920TEST(IsExplicitTemplateSpecialization,
3921 DoesNotMatchImplicitTemplateInstantiations) {
3922 EXPECT_TRUE(notMatches(
3923 "template <typename T> class X {}; X<int> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003924 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003925 EXPECT_TRUE(notMatches(
3926 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003927 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003928}
3929
3930TEST(IsExplicitTemplateSpecialization,
3931 MatchesExplicitTemplateSpecializations) {
3932 EXPECT_TRUE(matches(
3933 "template <typename T> class X {};"
3934 "template<> class X<int> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003935 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003936 EXPECT_TRUE(matches(
3937 "template <typename T> void f(T t) {}"
3938 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003939 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003940}
3941
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003942TEST(HasAncenstor, MatchesDeclarationAncestors) {
3943 EXPECT_TRUE(matches(
3944 "class A { class B { class C {}; }; };",
3945 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3946}
3947
3948TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3949 EXPECT_TRUE(notMatches(
3950 "class A { class B { class C {}; }; };",
3951 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3952}
3953
3954TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3955 EXPECT_TRUE(matches(
3956 "class A { class B { void f() { C c; } class C {}; }; };",
3957 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3958 hasAncestor(recordDecl(hasName("A"))))))));
3959}
3960
3961TEST(HasAncenstor, MatchesStatementAncestors) {
3962 EXPECT_TRUE(matches(
3963 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003964 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003965}
3966
3967TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3968 EXPECT_TRUE(matches(
3969 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003970 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003971}
3972
3973TEST(HasAncestor, BindsRecursiveCombinations) {
3974 EXPECT_TRUE(matchAndVerifyResultTrue(
3975 "class C { class D { class E { class F { int y; }; }; }; };",
3976 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003977 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003978}
3979
3980TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3981 EXPECT_TRUE(matchAndVerifyResultTrue(
3982 "class C { class D { class E { class F { int y; }; }; }; };",
3983 fieldDecl(hasAncestor(
3984 decl(
3985 hasDescendant(recordDecl(isDefinition(),
3986 hasAncestor(recordDecl())))
3987 ).bind("d")
3988 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003989 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003990}
3991
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003992TEST(HasAncestor, MatchesClosestAncestor) {
3993 EXPECT_TRUE(matchAndVerifyResultTrue(
3994 "template <typename T> struct C {"
3995 " void f(int) {"
3996 " struct I { void g(T) { int x; } } i; i.g(42);"
3997 " }"
3998 "};"
3999 "template struct C<int>;",
4000 varDecl(hasName("x"),
4001 hasAncestor(functionDecl(hasParameter(
4002 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
4003 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
4004}
4005
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004006TEST(HasAncestor, MatchesInTemplateInstantiations) {
4007 EXPECT_TRUE(matches(
4008 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
4009 "A<int>::B::C a;",
4010 fieldDecl(hasType(asString("int")),
4011 hasAncestor(recordDecl(hasName("A"))))));
4012}
4013
4014TEST(HasAncestor, MatchesInImplicitCode) {
4015 EXPECT_TRUE(matches(
4016 "struct X {}; struct A { A() {} X x; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00004017 cxxConstructorDecl(
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004018 hasAnyConstructorInitializer(withInitializer(expr(
4019 hasAncestor(recordDecl(hasName("A")))))))));
4020}
4021
Daniel Jasper632aea92012-10-22 16:26:51 +00004022TEST(HasParent, MatchesOnlyParent) {
4023 EXPECT_TRUE(matches(
4024 "void f() { if (true) { int x = 42; } }",
4025 compoundStmt(hasParent(ifStmt()))));
4026 EXPECT_TRUE(notMatches(
4027 "void f() { for (;;) { int x = 42; } }",
4028 compoundStmt(hasParent(ifStmt()))));
4029 EXPECT_TRUE(notMatches(
4030 "void f() { if (true) for (;;) { int x = 42; } }",
4031 compoundStmt(hasParent(ifStmt()))));
4032}
4033
Manuel Klimekc844a462012-12-06 14:42:48 +00004034TEST(HasAncestor, MatchesAllAncestors) {
4035 EXPECT_TRUE(matches(
4036 "template <typename T> struct C { static void f() { 42; } };"
4037 "void t() { C<int>::f(); }",
4038 integerLiteral(
4039 equals(42),
Aaron Ballman512fb642015-09-17 13:30:52 +00004040 allOf(
4041 hasAncestor(cxxRecordDecl(isTemplateInstantiation())),
4042 hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation())))))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004043}
4044
4045TEST(HasParent, MatchesAllParents) {
4046 EXPECT_TRUE(matches(
4047 "template <typename T> struct C { static void f() { 42; } };"
4048 "void t() { C<int>::f(); }",
4049 integerLiteral(
4050 equals(42),
4051 hasParent(compoundStmt(hasParent(functionDecl(
Aaron Ballman512fb642015-09-17 13:30:52 +00004052 hasParent(cxxRecordDecl(isTemplateInstantiation())))))))));
4053 EXPECT_TRUE(
4054 matches("template <typename T> struct C { static void f() { 42; } };"
4055 "void t() { C<int>::f(); }",
4056 integerLiteral(
4057 equals(42),
4058 hasParent(compoundStmt(hasParent(functionDecl(hasParent(
4059 cxxRecordDecl(unless(isTemplateInstantiation()))))))))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004060 EXPECT_TRUE(matches(
4061 "template <typename T> struct C { static void f() { 42; } };"
4062 "void t() { C<int>::f(); }",
4063 integerLiteral(equals(42),
Aaron Ballman512fb642015-09-17 13:30:52 +00004064 hasParent(compoundStmt(
4065 allOf(hasParent(functionDecl(hasParent(
4066 cxxRecordDecl(isTemplateInstantiation())))),
4067 hasParent(functionDecl(hasParent(cxxRecordDecl(
4068 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00004069 EXPECT_TRUE(
4070 notMatches("template <typename T> struct C { static void f() {} };"
4071 "void t() { C<int>::f(); }",
4072 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004073}
4074
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00004075TEST(HasParent, NoDuplicateParents) {
4076 class HasDuplicateParents : public BoundNodesCallback {
4077 public:
4078 bool run(const BoundNodes *Nodes) override { return false; }
4079 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
4080 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
4081 std::set<const void *> Parents;
4082 for (const auto &Parent : Context->getParents(*Node)) {
4083 if (!Parents.insert(Parent.getMemoizationData()).second) {
4084 return true;
4085 }
4086 }
4087 return false;
4088 }
4089 };
4090 EXPECT_FALSE(matchAndVerifyResultTrue(
4091 "template <typename T> int Foo() { return 1 + 2; }\n"
4092 "int x = Foo<int>() + Foo<unsigned>();",
4093 stmt().bind("node"), new HasDuplicateParents()));
4094}
4095
Daniel Jasper516b02e2012-10-17 08:52:59 +00004096TEST(TypeMatching, MatchesTypes) {
4097 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
4098}
4099
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004100TEST(TypeMatching, MatchesVoid) {
Aaron Ballman512fb642015-09-17 13:30:52 +00004101 EXPECT_TRUE(matches("struct S { void func(); };",
4102 cxxMethodDecl(returns(voidType()))));
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004103}
4104
Daniel Jasper516b02e2012-10-17 08:52:59 +00004105TEST(TypeMatching, MatchesArrayTypes) {
4106 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
4107 EXPECT_TRUE(matches("int a[42];", arrayType()));
4108 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
4109
4110 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
4111 arrayType(hasElementType(builtinType()))));
4112
4113 EXPECT_TRUE(matches(
4114 "int const a[] = { 2, 3 };",
4115 qualType(arrayType(hasElementType(builtinType())))));
4116 EXPECT_TRUE(matches(
4117 "int const a[] = { 2, 3 };",
4118 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4119 EXPECT_TRUE(matches(
4120 "typedef const int T; T x[] = { 1, 2 };",
4121 qualType(isConstQualified(), arrayType())));
4122
4123 EXPECT_TRUE(notMatches(
4124 "int a[] = { 2, 3 };",
4125 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4126 EXPECT_TRUE(notMatches(
4127 "int a[] = { 2, 3 };",
4128 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
4129 EXPECT_TRUE(notMatches(
4130 "int const a[] = { 2, 3 };",
4131 qualType(arrayType(hasElementType(builtinType())),
4132 unless(isConstQualified()))));
4133
4134 EXPECT_TRUE(matches("int a[2];",
4135 constantArrayType(hasElementType(builtinType()))));
4136 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
4137}
4138
Matthias Gehre2cf7e802015-10-12 21:46:07 +00004139TEST(TypeMatching, DecayedType) {
4140 EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
4141 EXPECT_TRUE(notMatches("int i[7];", decayedType()));
4142}
4143
Daniel Jasper516b02e2012-10-17 08:52:59 +00004144TEST(TypeMatching, MatchesComplexTypes) {
4145 EXPECT_TRUE(matches("_Complex float f;", complexType()));
4146 EXPECT_TRUE(matches(
4147 "_Complex float f;",
4148 complexType(hasElementType(builtinType()))));
4149 EXPECT_TRUE(notMatches(
4150 "_Complex float f;",
4151 complexType(hasElementType(isInteger()))));
4152}
4153
4154TEST(TypeMatching, MatchesConstantArrayTypes) {
4155 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
4156 EXPECT_TRUE(notMatches(
4157 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
4158 constantArrayType(hasElementType(builtinType()))));
4159
4160 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
4161 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
4162 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
4163}
4164
4165TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
4166 EXPECT_TRUE(matches(
4167 "template <typename T, int Size> class array { T data[Size]; };",
4168 dependentSizedArrayType()));
4169 EXPECT_TRUE(notMatches(
4170 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
4171 dependentSizedArrayType()));
4172}
4173
4174TEST(TypeMatching, MatchesIncompleteArrayType) {
4175 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
4176 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
4177
4178 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
4179 incompleteArrayType()));
4180}
4181
4182TEST(TypeMatching, MatchesVariableArrayType) {
4183 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
4184 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4185
4186 EXPECT_TRUE(matches(
4187 "void f(int b) { int a[b]; }",
4188 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4189 varDecl(hasName("b")))))))));
4190}
4191
4192TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00004193 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4194 llvm::Triple::Win32) {
4195 // FIXME: Make this work for MSVC.
4196 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004197
David Majnemer197e2102014-03-05 06:32:38 +00004198 EXPECT_TRUE(matches("_Atomic(int) i;",
4199 atomicType(hasValueType(isInteger()))));
4200 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4201 atomicType(hasValueType(isInteger()))));
4202 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004203}
4204
4205TEST(TypeMatching, MatchesAutoTypes) {
4206 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4207 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4208 autoType()));
4209
Richard Smith061f1e22013-04-30 21:23:01 +00004210 // FIXME: Matching against the type-as-written can't work here, because the
4211 // type as written was not deduced.
4212 //EXPECT_TRUE(matches("auto a = 1;",
4213 // autoType(hasDeducedType(isInteger()))));
4214 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4215 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004216}
4217
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004218TEST(TypeMatching, MatchesFunctionTypes) {
4219 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4220 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4221}
4222
Edwin Vaneec074802013-04-01 18:33:34 +00004223TEST(TypeMatching, MatchesParenType) {
4224 EXPECT_TRUE(
4225 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4226 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4227
4228 EXPECT_TRUE(matches(
4229 "int (*ptr_to_func)(int);",
4230 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4231 EXPECT_TRUE(notMatches(
4232 "int (*ptr_to_array)[4];",
4233 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4234}
4235
Daniel Jasper516b02e2012-10-17 08:52:59 +00004236TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004237 // FIXME: Reactive when these tests can be more specific (not matching
4238 // implicit code on certain platforms), likely when we have hasDescendant for
4239 // Types/TypeLocs.
4240 //EXPECT_TRUE(matchAndVerifyResultTrue(
4241 // "int* a;",
4242 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4243 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4244 //EXPECT_TRUE(matchAndVerifyResultTrue(
4245 // "int* a;",
4246 // pointerTypeLoc().bind("loc"),
4247 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004248 EXPECT_TRUE(matches(
4249 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004250 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004251 EXPECT_TRUE(matches(
4252 "int** a;",
4253 loc(pointerType(pointee(pointerType())))));
4254 EXPECT_TRUE(matches(
4255 "int* b; int* * const a = &b;",
4256 loc(qualType(isConstQualified(), pointerType()))));
4257
4258 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004259 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4260 hasType(blockPointerType()))));
4261 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4262 hasType(memberPointerType()))));
4263 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4264 hasType(pointerType()))));
4265 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4266 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004267 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4268 hasType(lValueReferenceType()))));
4269 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4270 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004271
Daniel Jasper7943eb52012-10-17 13:35:36 +00004272 Fragment = "int *ptr;";
4273 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4274 hasType(blockPointerType()))));
4275 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4276 hasType(memberPointerType()))));
4277 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4278 hasType(pointerType()))));
4279 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4280 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004281
Daniel Jasper7943eb52012-10-17 13:35:36 +00004282 Fragment = "int a; int &ref = a;";
4283 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4284 hasType(blockPointerType()))));
4285 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4286 hasType(memberPointerType()))));
4287 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4288 hasType(pointerType()))));
4289 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4290 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004291 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4292 hasType(lValueReferenceType()))));
4293 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4294 hasType(rValueReferenceType()))));
4295
4296 Fragment = "int &&ref = 2;";
4297 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4298 hasType(blockPointerType()))));
4299 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4300 hasType(memberPointerType()))));
4301 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4302 hasType(pointerType()))));
4303 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4304 hasType(referenceType()))));
4305 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4306 hasType(lValueReferenceType()))));
4307 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4308 hasType(rValueReferenceType()))));
4309}
4310
4311TEST(TypeMatching, AutoRefTypes) {
4312 std::string Fragment = "auto a = 1;"
4313 "auto b = a;"
4314 "auto &c = a;"
4315 "auto &&d = c;"
4316 "auto &&e = 2;";
4317 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4318 hasType(referenceType()))));
4319 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4320 hasType(referenceType()))));
4321 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4322 hasType(referenceType()))));
4323 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4324 hasType(lValueReferenceType()))));
4325 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4326 hasType(rValueReferenceType()))));
4327 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4328 hasType(referenceType()))));
4329 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4330 hasType(lValueReferenceType()))));
4331 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4332 hasType(rValueReferenceType()))));
4333 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4334 hasType(referenceType()))));
4335 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4336 hasType(lValueReferenceType()))));
4337 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4338 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004339}
4340
4341TEST(TypeMatching, PointeeTypes) {
4342 EXPECT_TRUE(matches("int b; int &a = b;",
4343 referenceType(pointee(builtinType()))));
4344 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4345
4346 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004347 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004348
4349 EXPECT_TRUE(matches(
4350 "int const *A;",
4351 pointerType(pointee(isConstQualified(), builtinType()))));
4352 EXPECT_TRUE(notMatches(
4353 "int *A;",
4354 pointerType(pointee(isConstQualified(), builtinType()))));
4355}
4356
4357TEST(TypeMatching, MatchesPointersToConstTypes) {
4358 EXPECT_TRUE(matches("int b; int * const a = &b;",
4359 loc(pointerType())));
4360 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004361 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004362 EXPECT_TRUE(matches(
4363 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004364 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004365 EXPECT_TRUE(matches(
4366 "int b; const int * a = &b;",
4367 pointerType(pointee(builtinType()))));
4368}
4369
4370TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004371 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4372 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004373}
4374
Edwin Vanef901b712013-02-25 14:49:29 +00004375TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004376 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004377 templateSpecializationType()));
4378}
4379
Edwin Vaneb6eae142013-02-25 20:43:32 +00004380TEST(TypeMatching, MatchesRecordType) {
4381 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004382 EXPECT_TRUE(matches("struct S{}; S s;",
4383 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4384 EXPECT_TRUE(notMatches("int i;",
4385 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004386}
4387
4388TEST(TypeMatching, MatchesElaboratedType) {
4389 EXPECT_TRUE(matches(
4390 "namespace N {"
4391 " namespace M {"
4392 " class D {};"
4393 " }"
4394 "}"
4395 "N::M::D d;", elaboratedType()));
4396 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4397 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4398}
4399
4400TEST(ElaboratedTypeNarrowing, hasQualifier) {
4401 EXPECT_TRUE(matches(
4402 "namespace N {"
4403 " namespace M {"
4404 " class D {};"
4405 " }"
4406 "}"
4407 "N::M::D d;",
4408 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4409 EXPECT_TRUE(notMatches(
4410 "namespace M {"
4411 " class D {};"
4412 "}"
4413 "M::D d;",
4414 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004415 EXPECT_TRUE(notMatches(
4416 "struct D {"
4417 "} d;",
4418 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004419}
4420
4421TEST(ElaboratedTypeNarrowing, namesType) {
4422 EXPECT_TRUE(matches(
4423 "namespace N {"
4424 " namespace M {"
4425 " class D {};"
4426 " }"
4427 "}"
4428 "N::M::D d;",
4429 elaboratedType(elaboratedType(namesType(recordType(
4430 hasDeclaration(namedDecl(hasName("D")))))))));
4431 EXPECT_TRUE(notMatches(
4432 "namespace M {"
4433 " class D {};"
4434 "}"
4435 "M::D d;",
4436 elaboratedType(elaboratedType(namesType(typedefType())))));
4437}
4438
Samuel Benzaquenf8ec4542015-08-26 16:15:59 +00004439TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
4440 const std::string code = "template <typename T>"
4441 "int F() {"
4442 " return 1 + T();"
4443 "}"
4444 "int i = F<int>();";
4445 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
4446 expr(hasType(substTemplateTypeParmType()))))));
4447 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
4448 expr(hasType(substTemplateTypeParmType()))))));
4449}
4450
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004451TEST(NNS, MatchesNestedNameSpecifiers) {
4452 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4453 nestedNameSpecifier()));
4454 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4455 nestedNameSpecifier()));
4456 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4457 nestedNameSpecifier()));
4458
4459 EXPECT_TRUE(matches(
4460 "struct A { static void f() {} }; void g() { A::f(); }",
4461 nestedNameSpecifier()));
4462 EXPECT_TRUE(notMatches(
4463 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4464 nestedNameSpecifier()));
4465}
4466
Daniel Jasper87c3d362012-09-20 14:12:57 +00004467TEST(NullStatement, SimpleCases) {
4468 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4469 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4470}
4471
Aaron Ballman11825f22015-08-18 19:55:20 +00004472TEST(NS, Anonymous) {
4473 EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
4474 EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
4475}
4476
Aaron Ballman6c79f352015-08-28 19:39:21 +00004477TEST(NS, Alias) {
4478 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
4479 namespaceAliasDecl(hasName("alias"))));
4480}
4481
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004482TEST(NNS, MatchesTypes) {
4483 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4484 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4485 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4486 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4487 Matcher));
4488 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4489}
4490
4491TEST(NNS, MatchesNamespaceDecls) {
4492 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4493 specifiesNamespace(hasName("ns")));
4494 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4495 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4496 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4497}
4498
4499TEST(NNS, BindsNestedNameSpecifiers) {
4500 EXPECT_TRUE(matchAndVerifyResultTrue(
4501 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4502 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4503 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4504}
4505
4506TEST(NNS, BindsNestedNameSpecifierLocs) {
4507 EXPECT_TRUE(matchAndVerifyResultTrue(
4508 "namespace ns { struct B {}; } ns::B b;",
4509 loc(nestedNameSpecifier()).bind("loc"),
4510 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4511}
4512
4513TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4514 EXPECT_TRUE(matches(
4515 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4516 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4517 EXPECT_TRUE(matches(
4518 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004519 nestedNameSpecifierLoc(hasPrefix(
4520 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004521}
4522
Daniel Jasper6fc34332012-10-30 15:42:00 +00004523TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4524 std::string Fragment =
4525 "namespace a { struct A { struct B { struct C {}; }; }; };"
4526 "void f() { a::A::B::C c; }";
4527 EXPECT_TRUE(matches(
4528 Fragment,
4529 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4530 hasDescendant(nestedNameSpecifier(
4531 specifiesNamespace(hasName("a")))))));
4532 EXPECT_TRUE(notMatches(
4533 Fragment,
4534 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4535 has(nestedNameSpecifier(
4536 specifiesNamespace(hasName("a")))))));
4537 EXPECT_TRUE(matches(
4538 Fragment,
4539 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4540 has(nestedNameSpecifier(
4541 specifiesNamespace(hasName("a")))))));
4542
4543 // Not really useful because a NestedNameSpecifier can af at most one child,
4544 // but to complete the interface.
4545 EXPECT_TRUE(matchAndVerifyResultTrue(
4546 Fragment,
4547 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4548 forEach(nestedNameSpecifier().bind("x"))),
4549 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4550}
4551
4552TEST(NNS, NestedNameSpecifiersAsDescendants) {
4553 std::string Fragment =
4554 "namespace a { struct A { struct B { struct C {}; }; }; };"
4555 "void f() { a::A::B::C c; }";
4556 EXPECT_TRUE(matches(
4557 Fragment,
4558 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4559 asString("struct a::A")))))));
4560 EXPECT_TRUE(matchAndVerifyResultTrue(
4561 Fragment,
4562 functionDecl(hasName("f"),
4563 forEachDescendant(nestedNameSpecifier().bind("x"))),
4564 // Nested names: a, a::A and a::A::B.
4565 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4566}
4567
4568TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4569 std::string Fragment =
4570 "namespace a { struct A { struct B { struct C {}; }; }; };"
4571 "void f() { a::A::B::C c; }";
4572 EXPECT_TRUE(matches(
4573 Fragment,
4574 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4575 hasDescendant(loc(nestedNameSpecifier(
4576 specifiesNamespace(hasName("a"))))))));
4577 EXPECT_TRUE(notMatches(
4578 Fragment,
4579 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4580 has(loc(nestedNameSpecifier(
4581 specifiesNamespace(hasName("a"))))))));
4582 EXPECT_TRUE(matches(
4583 Fragment,
4584 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4585 has(loc(nestedNameSpecifier(
4586 specifiesNamespace(hasName("a"))))))));
4587
4588 EXPECT_TRUE(matchAndVerifyResultTrue(
4589 Fragment,
4590 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4591 forEach(nestedNameSpecifierLoc().bind("x"))),
4592 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4593}
4594
4595TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4596 std::string Fragment =
4597 "namespace a { struct A { struct B { struct C {}; }; }; };"
4598 "void f() { a::A::B::C c; }";
4599 EXPECT_TRUE(matches(
4600 Fragment,
4601 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4602 asString("struct a::A"))))))));
4603 EXPECT_TRUE(matchAndVerifyResultTrue(
4604 Fragment,
4605 functionDecl(hasName("f"),
4606 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4607 // Nested names: a, a::A and a::A::B.
4608 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4609}
4610
Manuel Klimek191c0932013-02-01 13:41:35 +00004611template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004612public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004613 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4614 StringRef InnerId)
4615 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004616 }
4617
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004618 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004619
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004620 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004621 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004622 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4623 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004624 }
4625private:
4626 std::string Id;
4627 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004628 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004629};
4630
4631TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004632 EXPECT_TRUE(matchAndVerifyResultTrue(
4633 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4634 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004635 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4636 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004637 EXPECT_TRUE(matchAndVerifyResultFalse(
4638 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4639 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004640 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4641 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004642}
4643
4644TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004645 EXPECT_TRUE(matchAndVerifyResultTrue(
4646 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004647 new VerifyMatchOnNode<clang::Stmt>(
4648 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004649 EXPECT_TRUE(matchAndVerifyResultFalse(
4650 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004651 new VerifyMatchOnNode<clang::Stmt>(
4652 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004653}
4654
4655TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4656 EXPECT_TRUE(matchAndVerifyResultTrue(
4657 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4658 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004659 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004660 EXPECT_TRUE(matchAndVerifyResultFalse(
4661 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4662 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004663 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004664}
4665
Manuel Klimekbee08572013-02-07 12:42:10 +00004666template <typename T>
4667class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4668public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004669 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004670
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004671 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004672 const T *Node = Nodes->getNodeAs<T>("");
4673 return verify(*Nodes, *Context, Node);
4674 }
4675
4676 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004677 // Use the original typed pointer to verify we can pass pointers to subtypes
4678 // to equalsNode.
4679 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004680 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004681 "", match(stmt(hasParent(
4682 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004683 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004684 }
4685 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004686 // Use the original typed pointer to verify we can pass pointers to subtypes
4687 // to equalsNode.
4688 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004689 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004690 "", match(decl(hasParent(
4691 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004692 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004693 }
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00004694 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
4695 // Use the original typed pointer to verify we can pass pointers to subtypes
4696 // to equalsNode.
4697 const T *TypedNode = cast<T>(Node);
4698 const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
4699 return selectFirst<T>(
4700 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
4701 hasType(type(equalsNode(TypedNode)).bind(""))))))),
4702 *Dec, Context)) != nullptr;
4703 }
Manuel Klimekbee08572013-02-07 12:42:10 +00004704};
4705
4706TEST(IsEqualTo, MatchesNodesByIdentity) {
4707 EXPECT_TRUE(matchAndVerifyResultTrue(
4708 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004709 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4710 EXPECT_TRUE(matchAndVerifyResultTrue(
4711 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4712 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00004713 EXPECT_TRUE(matchAndVerifyResultTrue(
4714 "class X { class Y {} y; };",
4715 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
4716 new VerifyAncestorHasChildIsEqual<Type>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004717}
4718
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004719TEST(MatchFinder, CheckProfiling) {
4720 MatchFinder::MatchFinderOptions Options;
4721 llvm::StringMap<llvm::TimeRecord> Records;
4722 Options.CheckProfiling.emplace(Records);
4723 MatchFinder Finder(std::move(Options));
4724
4725 struct NamedCallback : public MatchFinder::MatchCallback {
4726 void run(const MatchFinder::MatchResult &Result) override {}
4727 StringRef getID() const override { return "MyID"; }
4728 } Callback;
4729 Finder.addMatcher(decl(), &Callback);
4730 std::unique_ptr<FrontendActionFactory> Factory(
4731 newFrontendActionFactory(&Finder));
4732 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4733
4734 EXPECT_EQ(1u, Records.size());
4735 EXPECT_EQ("MyID", Records.begin()->getKey());
4736}
4737
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004738class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4739public:
4740 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004741 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004742 EXPECT_TRUE(Called);
4743 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004744 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004745 bool Called;
4746};
4747
4748TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4749 MatchFinder Finder;
4750 VerifyStartOfTranslationUnit VerifyCallback;
4751 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004752 std::unique_ptr<FrontendActionFactory> Factory(
4753 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004754 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4755 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004756
4757 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004758 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004759 ASSERT_TRUE(AST.get());
4760 Finder.matchAST(AST->getASTContext());
4761 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004762}
4763
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004764class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4765public:
4766 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004767 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004768 EXPECT_FALSE(Called);
4769 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004770 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004771 bool Called;
4772};
4773
4774TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4775 MatchFinder Finder;
4776 VerifyEndOfTranslationUnit VerifyCallback;
4777 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004778 std::unique_ptr<FrontendActionFactory> Factory(
4779 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004780 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4781 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004782
4783 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004784 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004785 ASSERT_TRUE(AST.get());
4786 Finder.matchAST(AST->getASTContext());
4787 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004788}
4789
Manuel Klimekbbb75852013-06-20 14:06:32 +00004790TEST(EqualsBoundNodeMatcher, QualType) {
4791 EXPECT_TRUE(matches(
4792 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4793 hasInitializer(ignoringParenImpCasts(
4794 hasType(qualType(equalsBoundNode("type"))))))));
4795 EXPECT_TRUE(notMatches("int i = 1.f;",
4796 varDecl(hasType(qualType().bind("type")),
4797 hasInitializer(ignoringParenImpCasts(hasType(
4798 qualType(equalsBoundNode("type"))))))));
4799}
4800
4801TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4802 EXPECT_TRUE(notMatches(
4803 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4804 hasInitializer(ignoringParenImpCasts(
4805 hasType(qualType(equalsBoundNode("type"))))))));
4806}
4807
4808TEST(EqualsBoundNodeMatcher, Stmt) {
4809 EXPECT_TRUE(
4810 matches("void f() { if(true) {} }",
4811 stmt(allOf(ifStmt().bind("if"),
4812 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4813
4814 EXPECT_TRUE(notMatches(
4815 "void f() { if(true) { if (true) {} } }",
4816 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4817}
4818
4819TEST(EqualsBoundNodeMatcher, Decl) {
4820 EXPECT_TRUE(matches(
4821 "class X { class Y {}; };",
4822 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4823 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4824
4825 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4826 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4827 has(decl(equalsBoundNode("record")))))));
4828}
4829
4830TEST(EqualsBoundNodeMatcher, Type) {
4831 EXPECT_TRUE(matches(
4832 "class X { int a; int b; };",
4833 recordDecl(
4834 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4835 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4836
4837 EXPECT_TRUE(notMatches(
4838 "class X { int a; double b; };",
4839 recordDecl(
4840 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4841 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4842}
4843
4844TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004845 EXPECT_TRUE(matchAndVerifyResultTrue(
4846 "int f() {"
4847 " if (1) {"
4848 " int i = 9;"
4849 " }"
4850 " int j = 10;"
4851 " {"
4852 " float k = 9.0;"
4853 " }"
4854 " return 0;"
4855 "}",
4856 // Look for variable declarations within functions whose type is the same
4857 // as the function return type.
4858 functionDecl(returns(qualType().bind("type")),
4859 forEachDescendant(varDecl(hasType(
4860 qualType(equalsBoundNode("type")))).bind("decl"))),
4861 // Only i and j should match, not k.
4862 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4863}
4864
4865TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4866 EXPECT_TRUE(matchAndVerifyResultTrue(
4867 "void f() {"
4868 " int x;"
4869 " double d;"
4870 " x = d + x - d + x;"
4871 "}",
4872 functionDecl(
4873 hasName("f"), forEachDescendant(varDecl().bind("d")),
4874 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4875 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4876}
4877
Manuel Klimekce68f772014-03-25 14:39:26 +00004878TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4879 EXPECT_TRUE(matchAndVerifyResultTrue(
4880 "struct StringRef { int size() const; const char* data() const; };"
4881 "void f(StringRef v) {"
4882 " v.data();"
4883 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00004884 cxxMemberCallExpr(
4885 callee(cxxMethodDecl(hasName("data"))),
4886 on(declRefExpr(to(
4887 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
4888 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
4889 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
Manuel Klimekce68f772014-03-25 14:39:26 +00004890 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4891 .bind("data"),
4892 new VerifyIdIsBoundTo<Expr>("data", 1)));
4893
4894 EXPECT_FALSE(matches(
4895 "struct StringRef { int size() const; const char* data() const; };"
4896 "void f(StringRef v) {"
4897 " v.data();"
4898 " v.size();"
4899 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00004900 cxxMemberCallExpr(
4901 callee(cxxMethodDecl(hasName("data"))),
4902 on(declRefExpr(to(
4903 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
4904 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
4905 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
Manuel Klimekce68f772014-03-25 14:39:26 +00004906 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4907 .bind("data")));
4908}
4909
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004910TEST(TypeDefDeclMatcher, Match) {
4911 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4912 typedefDecl(hasName("typedefDeclTest"))));
4913}
4914
Aaron Ballman11825f22015-08-18 19:55:20 +00004915TEST(IsInlineMatcher, IsInline) {
4916 EXPECT_TRUE(matches("void g(); inline void f();",
4917 functionDecl(isInline(), hasName("f"))));
4918 EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
4919 namespaceDecl(isInline(), hasName("m"))));
4920}
4921
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004922// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4923#ifndef LLVM_ON_WIN32
4924
4925TEST(Matcher, IsExpansionInMainFileMatcher) {
4926 EXPECT_TRUE(matches("class X {};",
4927 recordDecl(hasName("X"), isExpansionInMainFile())));
4928 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4929 FileContentMappings M;
4930 M.push_back(std::make_pair("/other", "class X {};"));
4931 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4932 recordDecl(isExpansionInMainFile()), false,
4933 "-isystem/", M));
4934}
4935
4936TEST(Matcher, IsExpansionInSystemHeader) {
4937 FileContentMappings M;
4938 M.push_back(std::make_pair("/other", "class X {};"));
4939 EXPECT_TRUE(matchesConditionally(
4940 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4941 "-isystem/", M));
4942 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4943 recordDecl(isExpansionInSystemHeader()),
4944 false, "-I/", M));
4945 EXPECT_TRUE(notMatches("class X {};",
4946 recordDecl(isExpansionInSystemHeader())));
4947 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4948}
4949
4950TEST(Matcher, IsExpansionInFileMatching) {
4951 FileContentMappings M;
4952 M.push_back(std::make_pair("/foo", "class A {};"));
4953 M.push_back(std::make_pair("/bar", "class B {};"));
4954 EXPECT_TRUE(matchesConditionally(
4955 "#include <foo>\n"
4956 "#include <bar>\n"
4957 "class X {};",
4958 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4959 "-isystem/", M));
4960 EXPECT_TRUE(matchesConditionally(
4961 "#include <foo>\n"
4962 "#include <bar>\n"
4963 "class X {};",
4964 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4965 "-isystem/", M));
4966}
4967
4968#endif // LLVM_ON_WIN32
4969
Manuel Klimekbfa43572015-03-12 15:48:15 +00004970
4971TEST(ObjCMessageExprMatcher, SimpleExprs) {
4972 // don't find ObjCMessageExpr where none are present
4973 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
4974
4975 std::string Objc1String =
4976 "@interface Str "
4977 " - (Str *)uppercaseString:(Str *)str;"
4978 "@end "
4979 "@interface foo "
4980 "- (void)meth:(Str *)text;"
4981 "@end "
4982 " "
4983 "@implementation foo "
4984 "- (void) meth:(Str *)text { "
4985 " [self contents];"
4986 " Str *up = [text uppercaseString];"
4987 "} "
4988 "@end ";
4989 EXPECT_TRUE(matchesObjC(
4990 Objc1String,
4991 objcMessageExpr(anything())));
4992 EXPECT_TRUE(matchesObjC(
4993 Objc1String,
4994 objcMessageExpr(hasSelector("contents"))));
4995 EXPECT_TRUE(matchesObjC(
4996 Objc1String,
4997 objcMessageExpr(matchesSelector("cont*"))));
4998 EXPECT_FALSE(matchesObjC(
4999 Objc1String,
5000 objcMessageExpr(matchesSelector("?cont*"))));
5001 EXPECT_TRUE(notMatchesObjC(
5002 Objc1String,
5003 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
5004 EXPECT_TRUE(matchesObjC(
5005 Objc1String,
5006 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
5007 EXPECT_TRUE(matchesObjC(
5008 Objc1String,
Manuel Klimeke67a9d62015-09-08 10:11:26 +00005009 objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
5010 EXPECT_TRUE(matchesObjC(
5011 Objc1String,
Manuel Klimekbfa43572015-03-12 15:48:15 +00005012 objcMessageExpr(matchesSelector("uppercase*"),
5013 argumentCountIs(0)
5014 )));
5015
5016}
5017
Manuel Klimek04616e42012-07-06 05:48:52 +00005018} // end namespace ast_matchers
5019} // end namespace clang