blob: d51a5e28b5e5bc9886692e3d2f8c8ccf2dcb1454 [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({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000039 DeclarationMatcher IsDerivedFromEmpty = recordDecl(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) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000125 DeclarationMatcher IsDerivedFromX = recordDecl(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
Daniel Jasperd6b82cb2012-09-12 21:14:15 +0000133 DeclarationMatcher IsAX = recordDecl(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 =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000142 recordDecl(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> {};",
261 recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
262 EXPECT_TRUE(matches(
263 "struct A {};"
264 "template<int> struct X;"
265 "template<int i> struct X : public X<i-1> {};"
266 "template<> struct X<0> : public A {};"
267 "struct B : public X<42> {};",
268 recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
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"),
285 hasInitializer(hasType(recordDecl(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"),
289 hasInitializer(hasType(recordDecl(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"),
293 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
294 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"),
310 hasInitializer(hasType(recordDecl(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"),
314 hasInitializer(hasType(recordDecl(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"),
318 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
319 isDerivedFrom("Base2")))))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000322 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000325 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000329 recordDecl(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> {};",
335 recordDecl(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(); };",
340 recordDecl(hasMethod(hasName("func")))));
341 EXPECT_TRUE(notMatches("class A { void func(); };",
342 recordDecl(hasMethod(isPublic()))));
343}
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;",
352 recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
353}
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) {
467 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000468 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000469 EXPECT_TRUE(
470 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
471 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
472 EXPECT_TRUE(
473 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
474 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
475
Daniel Jasper84c763e2012-07-15 19:57:12 +0000476 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000477 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000478 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
479 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
480
Manuel Klimek04616e42012-07-06 05:48:52 +0000481 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000482 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
483 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000484 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
485 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
486 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
487 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
488 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
489 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000490
491 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
492 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
493 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
494 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Aaron Ballman8f4699a2015-07-02 14:02:41 +0000495
496 EXPECT_TRUE(
497 matches("void f() try { } catch (int) { } catch (...) { }",
498 catchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000499}
500
501TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000502 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000503 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
504 EXPECT_TRUE(matches("class X {};", HasClassX));
505
506 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000507 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000508 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
509 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
510 EXPECT_TRUE(
511 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
512}
513
514TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
515 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000516 recordDecl(
517 has(recordDecl(
518 has(recordDecl(hasName("X"))),
519 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000520 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000521 has(recordDecl(
522 has(recordDecl(hasName("A"))),
523 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000524 hasName("C"))),
525 hasName("F"));
526
527 EXPECT_TRUE(matches(
528 "class F {"
529 " class Z {"
530 " class X {};"
531 " class Y {};"
532 " };"
533 " class C {"
534 " class A {};"
535 " class B {};"
536 " };"
537 "};", Recursive));
538
539 EXPECT_TRUE(matches(
540 "class F {"
541 " class Z {"
542 " class A {};"
543 " class X {};"
544 " class Y {};"
545 " };"
546 " class C {"
547 " class X {};"
548 " class A {};"
549 " class B {};"
550 " };"
551 "};", Recursive));
552
553 EXPECT_TRUE(matches(
554 "class O1 {"
555 " class O2 {"
556 " class F {"
557 " class Z {"
558 " class A {};"
559 " class X {};"
560 " class Y {};"
561 " };"
562 " class C {"
563 " class X {};"
564 " class A {};"
565 " class B {};"
566 " };"
567 " };"
568 " };"
569 "};", Recursive));
570}
571
572TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
573 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000574 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000575 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000576 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000577 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000578 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000579 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000580 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000581 hasName("Y"))),
582 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000583 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000584 anyOf(
585 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000586 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000587 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000588 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000589 hasName("B")))))),
590 hasName("F")));
591
592 EXPECT_TRUE(matches("class F {};", Recursive));
593 EXPECT_TRUE(matches("class Z {};", Recursive));
594 EXPECT_TRUE(matches("class C {};", Recursive));
595 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
596 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
597 EXPECT_TRUE(
598 matches("class O1 { class O2 {"
599 " class M { class N { class B {}; }; }; "
600 "}; };", Recursive));
601}
602
603TEST(DeclarationMatcher, MatchNot) {
604 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000605 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000606 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000607 unless(hasName("X")));
608 EXPECT_TRUE(notMatches("", NotClassX));
609 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
610 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
611 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
612 EXPECT_TRUE(
613 notMatches("class Y {}; class Z {}; class X : public Y {};",
614 NotClassX));
615
616 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000617 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000618 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000619 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000620 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000621 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000622 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
623 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
624 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000625
626 DeclarationMatcher NamedNotRecord =
627 namedDecl(hasName("Foo"), unless(recordDecl()));
628 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
629 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000630}
631
632TEST(DeclarationMatcher, HasDescendant) {
633 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000634 recordDecl(
635 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000636 hasName("Z"));
637 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
638 EXPECT_TRUE(
639 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
640 EXPECT_TRUE(
641 matches("class Z { class A { class Y { class X {}; }; }; };",
642 ZDescendantClassX));
643 EXPECT_TRUE(
644 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
645 ZDescendantClassX));
646 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
647
648 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000649 recordDecl(
650 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000651 hasName("X"))),
652 hasName("Z"));
653 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
654 ZDescendantClassXHasClassY));
655 EXPECT_TRUE(
656 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
657 ZDescendantClassXHasClassY));
658 EXPECT_TRUE(notMatches(
659 "class Z {"
660 " class A {"
661 " class B {"
662 " class X {"
663 " class C {"
664 " class Y {};"
665 " };"
666 " };"
667 " }; "
668 " };"
669 "};", ZDescendantClassXHasClassY));
670
671 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000672 recordDecl(
673 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
674 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000675 hasName("Z"));
676 EXPECT_TRUE(
677 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
678 ZDescendantClassXDescendantClassY));
679 EXPECT_TRUE(matches(
680 "class Z {"
681 " class A {"
682 " class X {"
683 " class B {"
684 " class Y {};"
685 " };"
686 " class Y {};"
687 " };"
688 " };"
689 "};", ZDescendantClassXDescendantClassY));
690}
691
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000692TEST(DeclarationMatcher, HasDescendantMemoization) {
693 DeclarationMatcher CannotMemoize =
694 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
695 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
696}
697
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000698TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
699 auto Name = hasName("i");
700 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
701 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
702 // Matching VD first should not make a cache hit for RD.
703 EXPECT_TRUE(notMatches("void f() { int i; }",
704 decl(hasDescendant(VD), hasDescendant(RD))));
705 EXPECT_TRUE(notMatches("void f() { int i; }",
706 decl(hasDescendant(RD), hasDescendant(VD))));
707 // Not matching RD first should not make a cache hit for VD either.
708 EXPECT_TRUE(matches("void f() { int i; }",
709 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
710}
711
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000712TEST(DeclarationMatcher, HasAttr) {
713 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
714 decl(hasAttr(clang::attr::WarnUnused))));
715 EXPECT_FALSE(matches("struct X {};",
716 decl(hasAttr(clang::attr::WarnUnused))));
717}
718
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000719TEST(DeclarationMatcher, MatchCudaDecl) {
720 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
721 "void g() { f<<<1, 2>>>(); }",
722 CUDAKernelCallExpr()));
723 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000724 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000725 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000726 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000727 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000728 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000729}
730
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000731// Implements a run method that returns whether BoundNodes contains a
732// Decl bound to Id that can be dynamically cast to T.
733// Optionally checks that the check succeeded a specific number of times.
734template <typename T>
735class VerifyIdIsBoundTo : public BoundNodesCallback {
736public:
737 // Create an object that checks that a node of type \c T was bound to \c Id.
738 // Does not check for a certain number of matches.
739 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
740 : Id(Id), ExpectedCount(-1), Count(0) {}
741
742 // Create an object that checks that a node of type \c T was bound to \c Id.
743 // Checks that there were exactly \c ExpectedCount matches.
744 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
745 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
746
747 // Create an object that checks that a node of type \c T was bound to \c Id.
748 // Checks that there was exactly one match with the name \c ExpectedName.
749 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000750 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
751 int ExpectedCount = 1)
752 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
753 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000754
Craig Toppera798a9d2014-03-02 09:32:10 +0000755 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000756 if (ExpectedCount != -1)
757 EXPECT_EQ(ExpectedCount, Count);
758 if (!ExpectedName.empty())
759 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000760 Count = 0;
761 Name.clear();
762 }
763
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000764 ~VerifyIdIsBoundTo() override {
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000765 EXPECT_EQ(0, Count);
766 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000767 }
768
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000769 bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000770 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000771 if (Nodes->getNodeAs<T>(Id)) {
772 ++Count;
773 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
774 Name = Named->getNameAsString();
775 } else if (const NestedNameSpecifier *NNS =
776 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
777 llvm::raw_string_ostream OS(Name);
778 NNS->print(OS, PrintingPolicy(LangOptions()));
779 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000780 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
781 EXPECT_NE(M.end(), I);
782 if (I != M.end())
783 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000784 return true;
785 }
Craig Topper416fa342014-06-08 08:38:12 +0000786 EXPECT_TRUE(M.count(Id) == 0 ||
787 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000788 return false;
789 }
790
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000791 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000792 return run(Nodes);
793 }
794
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000795private:
796 const std::string Id;
797 const int ExpectedCount;
798 int Count;
799 const std::string ExpectedName;
800 std::string Name;
801};
802
803TEST(HasDescendant, MatchesDescendantTypes) {
804 EXPECT_TRUE(matches("void f() { int i = 3; }",
805 decl(hasDescendant(loc(builtinType())))));
806 EXPECT_TRUE(matches("void f() { int i = 3; }",
807 stmt(hasDescendant(builtinType()))));
808
809 EXPECT_TRUE(matches("void f() { int i = 3; }",
810 stmt(hasDescendant(loc(builtinType())))));
811 EXPECT_TRUE(matches("void f() { int i = 3; }",
812 stmt(hasDescendant(qualType(builtinType())))));
813
814 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
815 stmt(hasDescendant(isInteger()))));
816
817 EXPECT_TRUE(matchAndVerifyResultTrue(
818 "void f() { int a; float c; int d; int e; }",
819 functionDecl(forEachDescendant(
820 varDecl(hasDescendant(isInteger())).bind("x"))),
821 new VerifyIdIsBoundTo<Decl>("x", 3)));
822}
823
824TEST(HasDescendant, MatchesDescendantsOfTypes) {
825 EXPECT_TRUE(matches("void f() { int*** i; }",
826 qualType(hasDescendant(builtinType()))));
827 EXPECT_TRUE(matches("void f() { int*** i; }",
828 qualType(hasDescendant(
829 pointerType(pointee(builtinType()))))));
830 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000831 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000832
833 EXPECT_TRUE(matchAndVerifyResultTrue(
834 "void f() { int*** i; }",
835 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
836 new VerifyIdIsBoundTo<Type>("x", 2)));
837}
838
839TEST(Has, MatchesChildrenOfTypes) {
840 EXPECT_TRUE(matches("int i;",
841 varDecl(hasName("i"), has(isInteger()))));
842 EXPECT_TRUE(notMatches("int** i;",
843 varDecl(hasName("i"), has(isInteger()))));
844 EXPECT_TRUE(matchAndVerifyResultTrue(
845 "int (*f)(float, int);",
846 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
847 new VerifyIdIsBoundTo<QualType>("x", 2)));
848}
849
850TEST(Has, MatchesChildTypes) {
851 EXPECT_TRUE(matches(
852 "int* i;",
853 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
854 EXPECT_TRUE(notMatches(
855 "int* i;",
856 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
857}
858
Samuel Benzaquenc640ef52014-10-28 13:33:58 +0000859TEST(ValueDecl, Matches) {
860 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
861 valueDecl(hasType(asString("enum EnumType")))));
862 EXPECT_TRUE(matches("void FunctionDecl();",
863 valueDecl(hasType(asString("void (void)")))));
864}
865
Daniel Jasper1dad1832012-07-10 20:20:19 +0000866TEST(Enum, DoesNotMatchClasses) {
867 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
868}
869
870TEST(Enum, MatchesEnums) {
871 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
872}
873
874TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000875 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000876 EXPECT_TRUE(matches("enum X{ A };", Matcher));
877 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
878 EXPECT_TRUE(notMatches("enum X {};", Matcher));
879}
880
Manuel Klimek04616e42012-07-06 05:48:52 +0000881TEST(StatementMatcher, Has) {
882 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000883 expr(hasType(pointsTo(recordDecl(hasName("X")))),
884 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000885
886 EXPECT_TRUE(matches(
887 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
888 EXPECT_TRUE(notMatches(
889 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
890}
891
892TEST(StatementMatcher, HasDescendant) {
893 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000894 expr(hasType(pointsTo(recordDecl(hasName("X")))),
895 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000896
897 EXPECT_TRUE(matches(
898 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
899 HasDescendantVariableI));
900 EXPECT_TRUE(notMatches(
901 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
902 HasDescendantVariableI));
903}
904
905TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000906 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000907
908 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
909 EXPECT_TRUE(notMatches("class A {};", TypeA));
910
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000911 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(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));
922}
923
Manuel Klimek04616e42012-07-06 05:48:52 +0000924TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000925 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000926
927 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000928 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000929
930 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000931 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000932
933 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000934 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000935
936 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
937 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000938 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000939
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000940 StatementMatcher MethodX =
941 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000942
943 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
944 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000945 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000946}
947
948TEST(Matcher, BindTheSameNameInAlternatives) {
949 StatementMatcher matcher = anyOf(
950 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000951 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000952 hasRHS(integerLiteral(equals(0)))),
953 binaryOperator(hasOperatorName("+"),
954 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000955 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000956
957 EXPECT_TRUE(matchAndVerifyResultTrue(
958 // The first branch of the matcher binds x to 0 but then fails.
959 // The second branch binds x to f() and succeeds.
960 "int f() { return 0 + f(); }",
961 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000962 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000963}
964
Manuel Klimekfdf98762012-08-30 19:41:06 +0000965TEST(Matcher, BindsIDForMemoizedResults) {
966 // Using the same matcher in two match expressions will make memoization
967 // kick in.
968 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
969 EXPECT_TRUE(matchAndVerifyResultTrue(
970 "class A { class B { class X {}; }; };",
971 DeclarationMatcher(anyOf(
972 recordDecl(hasName("A"), hasDescendant(ClassX)),
973 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000974 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000975}
976
Daniel Jasper856194d02012-12-03 15:43:25 +0000977TEST(HasDeclaration, HasDeclarationOfEnumType) {
978 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
979 expr(hasType(pointsTo(
980 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
981}
982
Edwin Vaneed936452013-02-25 14:32:42 +0000983TEST(HasDeclaration, HasGetDeclTraitTest) {
984 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
985 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
986 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
987}
988
Edwin Vane2c197e02013-02-19 17:14:34 +0000989TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
990 EXPECT_TRUE(matches("typedef int X; X a;",
991 varDecl(hasName("a"),
992 hasType(typedefType(hasDeclaration(decl()))))));
993
994 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
995}
996
Edwin Vanef901b712013-02-25 14:49:29 +0000997TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
998 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
999 varDecl(hasType(templateSpecializationType(
1000 hasDeclaration(namedDecl(hasName("A"))))))));
1001}
1002
Manuel Klimek04616e42012-07-06 05:48:52 +00001003TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001004 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001005 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001006 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001007 EXPECT_TRUE(
1008 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001009 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001010 EXPECT_TRUE(
1011 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001012 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001013}
1014
1015TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001016 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001017 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001018 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001019 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001020 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001021 EXPECT_TRUE(
1022 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001023 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001024}
1025
1026TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001027 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001028 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001029 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001030 EXPECT_TRUE(
1031 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001032 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001033}
1034
1035TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001036 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001037 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001038 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001039 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001040 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001041}
1042
Manuel Klimekc16c6522013-06-20 13:08:29 +00001043TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1044 EXPECT_TRUE(matches("int x;",
1045 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1046
1047 // Make sure we don't crash on implicit constructors.
1048 EXPECT_TRUE(notMatches("class X {}; X x;",
1049 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1050}
1051
Manuel Klimek04616e42012-07-06 05:48:52 +00001052TEST(Matcher, Call) {
1053 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001054 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001055 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001056
1057 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1058 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1059
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001060 StatementMatcher MethodOnY =
1061 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001062
1063 EXPECT_TRUE(
1064 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1065 MethodOnY));
1066 EXPECT_TRUE(
1067 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1068 MethodOnY));
1069 EXPECT_TRUE(
1070 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1071 MethodOnY));
1072 EXPECT_TRUE(
1073 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1074 MethodOnY));
1075 EXPECT_TRUE(
1076 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1077 MethodOnY));
1078
1079 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001080 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001081
1082 EXPECT_TRUE(
1083 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1084 MethodOnYPointer));
1085 EXPECT_TRUE(
1086 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1087 MethodOnYPointer));
1088 EXPECT_TRUE(
1089 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1090 MethodOnYPointer));
1091 EXPECT_TRUE(
1092 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1093 MethodOnYPointer));
1094 EXPECT_TRUE(
1095 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1096 MethodOnYPointer));
1097}
1098
Daniel Jasper5901e472012-10-01 13:40:41 +00001099TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001100 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001101 lambdaExpr()));
1102}
1103
1104TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001105 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1106 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001107 forRangeStmt()));
1108 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1109 forRangeStmt()));
1110}
1111
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001112TEST(Matcher, SubstNonTypeTemplateParm) {
1113 EXPECT_FALSE(matches("template<int N>\n"
1114 "struct A { static const int n = 0; };\n"
1115 "struct B : public A<42> {};",
1116 substNonTypeTemplateParmExpr()));
1117 EXPECT_TRUE(matches("template<int N>\n"
1118 "struct A { static const int n = N; };\n"
1119 "struct B : public A<42> {};",
1120 substNonTypeTemplateParmExpr()));
1121}
1122
Daniel Jasper5901e472012-10-01 13:40:41 +00001123TEST(Matcher, UserDefinedLiteral) {
1124 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1125 " return i + 1;"
1126 "}"
1127 "char c = 'a'_inc;",
1128 userDefinedLiteral()));
1129}
1130
Daniel Jasper87c3d362012-09-20 14:12:57 +00001131TEST(Matcher, FlowControl) {
1132 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1133 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1134 continueStmt()));
1135 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1136 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1137 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1138}
1139
Daniel Jasper1dad1832012-07-10 20:20:19 +00001140TEST(HasType, MatchesAsString) {
1141 EXPECT_TRUE(
1142 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001143 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001144 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001145 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001146 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001147 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001148 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001149 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001150}
1151
Manuel Klimek04616e42012-07-06 05:48:52 +00001152TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001153 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001154 // Unary operator
1155 EXPECT_TRUE(matches("class Y { }; "
1156 "bool operator!(Y x) { return false; }; "
1157 "Y y; bool c = !y;", OpCall));
1158 // No match -- special operators like "new", "delete"
1159 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1160 // we need to figure out include paths in the test.
1161 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1162 // "class Y { }; "
1163 // "void *operator new(size_t size) { return 0; } "
1164 // "Y *y = new Y;", OpCall));
1165 EXPECT_TRUE(notMatches("class Y { }; "
1166 "void operator delete(void *p) { } "
1167 "void a() {Y *y = new Y; delete y;}", OpCall));
1168 // Binary operator
1169 EXPECT_TRUE(matches("class Y { }; "
1170 "bool operator&&(Y x, Y y) { return true; }; "
1171 "Y a; Y b; bool c = a && b;",
1172 OpCall));
1173 // No match -- normal operator, not an overloaded one.
1174 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1175 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1176}
1177
1178TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1179 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001180 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001181 EXPECT_TRUE(matches("class Y { }; "
1182 "bool operator&&(Y x, Y y) { return true; }; "
1183 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1184 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001185 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001186 EXPECT_TRUE(notMatches("class Y { }; "
1187 "bool operator&&(Y x, Y y) { return true; }; "
1188 "Y a; Y b; bool c = a && b;",
1189 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001190 StatementMatcher OpStarCall =
1191 operatorCallExpr(hasOverloadedOperatorName("*"));
1192 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1193 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001194 DeclarationMatcher ClassWithOpStar =
1195 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1196 EXPECT_TRUE(matches("class Y { int operator*(); };",
1197 ClassWithOpStar));
1198 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1199 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001200 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1201 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1202 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001203}
1204
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001205TEST(Matcher, NestedOverloadedOperatorCalls) {
1206 EXPECT_TRUE(matchAndVerifyResultTrue(
1207 "class Y { }; "
1208 "Y& operator&&(Y& x, Y& y) { return x; }; "
1209 "Y a; Y b; Y c; Y d = a && b && c;",
1210 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1211 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1212 EXPECT_TRUE(matches(
1213 "class Y { }; "
1214 "Y& operator&&(Y& x, Y& y) { return x; }; "
1215 "Y a; Y b; Y c; Y d = a && b && c;",
1216 operatorCallExpr(hasParent(operatorCallExpr()))));
1217 EXPECT_TRUE(matches(
1218 "class Y { }; "
1219 "Y& operator&&(Y& x, Y& y) { return x; }; "
1220 "Y a; Y b; Y c; Y d = a && b && c;",
1221 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1222}
1223
Manuel Klimek04616e42012-07-06 05:48:52 +00001224TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001225 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001226 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001227
1228 EXPECT_TRUE(
1229 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1230 MethodOnY));
1231 EXPECT_TRUE(
1232 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1233 MethodOnY));
1234 EXPECT_TRUE(
1235 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1236 MethodOnY));
1237 EXPECT_TRUE(
1238 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1239 MethodOnY));
1240 EXPECT_TRUE(
1241 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1242 MethodOnY));
1243
1244 EXPECT_TRUE(matches(
1245 "class Y {"
1246 " public: virtual void x();"
1247 "};"
1248 "class X : public Y {"
1249 " public: virtual void x();"
1250 "};"
1251 "void z() { X *x; x->Y::x(); }", MethodOnY));
1252}
1253
1254TEST(Matcher, VariableUsage) {
1255 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001256 declRefExpr(to(
1257 varDecl(hasInitializer(
1258 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001259
1260 EXPECT_TRUE(matches(
1261 "class Y {"
1262 " public:"
1263 " bool x() const;"
1264 "};"
1265 "void z(const Y &y) {"
1266 " bool b = y.x();"
1267 " if (b) {}"
1268 "}", Reference));
1269
1270 EXPECT_TRUE(notMatches(
1271 "class Y {"
1272 " public:"
1273 " bool x() const;"
1274 "};"
1275 "void z(const Y &y) {"
1276 " bool b = y.x();"
1277 "}", Reference));
1278}
1279
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001280TEST(Matcher, VarDecl_Storage) {
1281 auto M = varDecl(hasName("X"), hasLocalStorage());
1282 EXPECT_TRUE(matches("void f() { int X; }", M));
1283 EXPECT_TRUE(notMatches("int X;", M));
1284 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1285
1286 M = varDecl(hasName("X"), hasGlobalStorage());
1287 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1288 EXPECT_TRUE(matches("int X;", M));
1289 EXPECT_TRUE(matches("void f() { static int X; }", M));
1290}
1291
Manuel Klimek61379422012-12-04 14:42:08 +00001292TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001293 EXPECT_TRUE(matches(
1294 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001295 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001296}
1297
Manuel Klimek04616e42012-07-06 05:48:52 +00001298TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001299 StatementMatcher CallOnVariableY =
1300 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001301
1302 EXPECT_TRUE(matches(
1303 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1304 EXPECT_TRUE(matches(
1305 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1306 EXPECT_TRUE(matches(
1307 "class Y { public: void x(); };"
1308 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1309 EXPECT_TRUE(matches(
1310 "class Y { public: void x(); };"
1311 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1312 EXPECT_TRUE(notMatches(
1313 "class Y { public: void x(); };"
1314 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1315 CallOnVariableY));
1316}
1317
Daniel Jasper1dad1832012-07-10 20:20:19 +00001318TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1319 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1320 unaryExprOrTypeTraitExpr()));
1321 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1322 alignOfExpr(anything())));
1323 // FIXME: Uncomment once alignof is enabled.
1324 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1325 // unaryExprOrTypeTraitExpr()));
1326 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1327 // sizeOfExpr()));
1328}
1329
1330TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1331 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1332 hasArgumentOfType(asString("int")))));
1333 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1334 hasArgumentOfType(asString("float")))));
1335 EXPECT_TRUE(matches(
1336 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001337 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001338 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001339 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001340}
1341
Manuel Klimek04616e42012-07-06 05:48:52 +00001342TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001343 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001344}
1345
1346TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001347 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001348}
1349
1350TEST(MemberExpression, MatchesVariable) {
1351 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001352 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001353 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001354 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001355 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001356 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001357}
1358
1359TEST(MemberExpression, MatchesStaticVariable) {
1360 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001361 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001362 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001363 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001364 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001365 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001366}
1367
Daniel Jasper4e566c42012-07-12 08:50:38 +00001368TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001369 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1370 EXPECT_TRUE(matches(
1371 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1372 callExpr(hasArgument(0, declRefExpr(
1373 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001374}
1375
1376TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001377 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001378 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001379 callExpr(hasArgument(0, declRefExpr(
1380 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001381}
1382
Manuel Klimek04616e42012-07-06 05:48:52 +00001383TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1384 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001385 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001386 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001387 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001388 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001389 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001390}
1391
1392TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1393 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001394 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001395 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001396 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001397 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001398 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001399}
1400
1401TEST(IsArrow, MatchesMemberCallsViaArrow) {
1402 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001403 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001404 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001405 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001406 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001407 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001408}
1409
1410TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001411 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001412
1413 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1414 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001415
1416 CallMethodX = callExpr(callee(conversionDecl()));
1417 EXPECT_TRUE(
1418 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1419 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1420 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001421}
1422
1423TEST(Callee, MatchesMemberExpressions) {
1424 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001425 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001426 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001427 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001428}
1429
1430TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001431 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001432
1433 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1434 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1435
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001436 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1437 llvm::Triple::Win32) {
1438 // FIXME: Make this work for MSVC.
1439 // Dependent contexts, but a non-dependent call.
1440 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1441 CallFunctionF));
1442 EXPECT_TRUE(
1443 matches("void f(); template <int N> struct S { void g() { f(); } };",
1444 CallFunctionF));
1445 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001446
1447 // Depedent calls don't match.
1448 EXPECT_TRUE(
1449 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1450 CallFunctionF));
1451 EXPECT_TRUE(
1452 notMatches("void f(int);"
1453 "template <typename T> struct S { void g(T t) { f(t); } };",
1454 CallFunctionF));
1455}
1456
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001457TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1458 EXPECT_TRUE(
1459 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001460 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001461}
1462
1463TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1464 EXPECT_TRUE(
1465 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001466 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001467}
1468
1469TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1470 EXPECT_TRUE(
1471 notMatches("void g(); template <typename T> void f(T t) {}"
1472 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001473 functionTemplateDecl(hasName("f"),
1474 hasDescendant(declRefExpr(to(
1475 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001476}
1477
Manuel Klimek04616e42012-07-06 05:48:52 +00001478TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001479 StatementMatcher CallArgumentY = callExpr(
1480 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001481
1482 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1483 EXPECT_TRUE(
1484 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1485 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1486
Daniel Jasper848cbe12012-09-18 13:09:13 +00001487 StatementMatcher WrongIndex = callExpr(
1488 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001489 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1490}
1491
1492TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001493 StatementMatcher CallArgumentY = callExpr(
1494 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001495 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1496 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1497 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1498}
1499
1500TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001501 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001502
1503 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1504 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1505 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1506}
1507
Daniel Jasper9f501292012-12-04 11:54:27 +00001508TEST(Matcher, ParameterCount) {
1509 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1510 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1511 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1512 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1513 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1514}
1515
Manuel Klimek04616e42012-07-06 05:48:52 +00001516TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001517 DeclarationMatcher ReferenceClassX = varDecl(
1518 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001519 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1520 ReferenceClassX));
1521 EXPECT_TRUE(
1522 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001523 // The match here is on the implicit copy constructor code for
1524 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001525 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001526 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1527 EXPECT_TRUE(
1528 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001529 EXPECT_TRUE(
1530 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1531}
1532
Edwin Vane0a4836e2013-03-06 17:02:57 +00001533TEST(QualType, hasCanonicalType) {
1534 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1535 "int a;"
1536 "int_ref b = a;",
1537 varDecl(hasType(qualType(referenceType())))));
1538 EXPECT_TRUE(
1539 matches("typedef int &int_ref;"
1540 "int a;"
1541 "int_ref b = a;",
1542 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1543}
1544
Edwin Vane119d3df2013-04-02 18:15:55 +00001545TEST(QualType, hasLocalQualifiers) {
1546 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1547 varDecl(hasType(hasLocalQualifiers()))));
1548 EXPECT_TRUE(matches("int *const j = nullptr;",
1549 varDecl(hasType(hasLocalQualifiers()))));
1550 EXPECT_TRUE(matches("int *volatile k;",
1551 varDecl(hasType(hasLocalQualifiers()))));
1552 EXPECT_TRUE(notMatches("int m;",
1553 varDecl(hasType(hasLocalQualifiers()))));
1554}
1555
Manuel Klimek04616e42012-07-06 05:48:52 +00001556TEST(HasParameter, CallsInnerMatcher) {
1557 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001558 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001559 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001560 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001561}
1562
1563TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1564 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001565 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001566}
1567
1568TEST(HasType, MatchesParameterVariableTypesStrictly) {
1569 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001570 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001571 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001572 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001573 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001574 methodDecl(hasParameter(0,
1575 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001576 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001577 methodDecl(hasParameter(0,
1578 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001579}
1580
1581TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1582 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001583 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001584 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001585 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001586}
1587
Daniel Jasper1dad1832012-07-10 20:20:19 +00001588TEST(Returns, MatchesReturnTypes) {
1589 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001590 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001591 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001592 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001593 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001594 functionDecl(returns(hasDeclaration(
1595 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001596}
1597
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001598TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001599 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1600 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1601 functionDecl(isExternC())));
1602 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001603}
1604
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001605TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1606 EXPECT_TRUE(
1607 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1608 EXPECT_TRUE(matches("void Func() = delete;",
1609 functionDecl(hasName("Func"), isDeleted())));
1610}
1611
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001612TEST(isConstexpr, MatchesConstexprDeclarations) {
1613 EXPECT_TRUE(matches("constexpr int foo = 42;",
1614 varDecl(hasName("foo"), isConstexpr())));
1615 EXPECT_TRUE(matches("constexpr int bar();",
1616 functionDecl(hasName("bar"), isConstexpr())));
1617}
1618
Manuel Klimek04616e42012-07-06 05:48:52 +00001619TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1620 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001621 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001622}
1623
1624TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1625 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001626 methodDecl(hasAnyParameter(hasType(pointsTo(
1627 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001628}
1629
Alp Toker8db6e7a2014-01-05 06:38:57 +00001630TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001631 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001632 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001633 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001634 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001635}
1636
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001637TEST(Matcher, MatchesClassTemplateSpecialization) {
1638 EXPECT_TRUE(matches("template<typename T> struct A {};"
1639 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001640 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001641 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001642 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001643 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001644 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001645}
1646
Manuel Klimekc16c6522013-06-20 13:08:29 +00001647TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1648 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1649 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1650}
1651
1652TEST(ParmVarDecl, MatchesParmVars) {
1653 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1654 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1655}
1656
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001657TEST(Matcher, MatchesTypeTemplateArgument) {
1658 EXPECT_TRUE(matches(
1659 "template<typename T> struct B {};"
1660 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001661 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001662 asString("int"))))));
1663}
1664
1665TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1666 EXPECT_TRUE(matches(
1667 "struct B { int next; };"
1668 "template<int(B::*next_ptr)> struct A {};"
1669 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001670 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1671 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001672
1673 EXPECT_TRUE(notMatches(
1674 "template <typename T> struct A {};"
1675 "A<int> a;",
1676 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1677 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001678
1679 EXPECT_TRUE(matches(
1680 "struct B { int next; };"
1681 "template<int(B::*next_ptr)> struct A {};"
1682 "A<&B::next> a;",
1683 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1684 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1685
1686 EXPECT_TRUE(notMatches(
1687 "template <typename T> struct A {};"
1688 "A<int> a;",
1689 templateSpecializationType(hasAnyTemplateArgument(
1690 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001691}
1692
1693TEST(Matcher, MatchesSpecificArgument) {
1694 EXPECT_TRUE(matches(
1695 "template<typename T, typename U> class A {};"
1696 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001697 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001698 1, refersToType(asString("int"))))));
1699 EXPECT_TRUE(notMatches(
1700 "template<typename T, typename U> class A {};"
1701 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001702 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001703 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001704
1705 EXPECT_TRUE(matches(
1706 "template<typename T, typename U> class A {};"
1707 "A<bool, int> a;",
1708 templateSpecializationType(hasTemplateArgument(
1709 1, refersToType(asString("int"))))));
1710 EXPECT_TRUE(notMatches(
1711 "template<typename T, typename U> class A {};"
1712 "A<int, bool> a;",
1713 templateSpecializationType(hasTemplateArgument(
1714 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001715}
1716
Manuel Klimek7735e402014-10-09 13:06:22 +00001717TEST(TemplateArgument, Matches) {
1718 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1719 classTemplateSpecializationDecl(
1720 hasAnyTemplateArgument(templateArgument()))));
1721 EXPECT_TRUE(matches(
1722 "template<typename T> struct C {}; C<int> c;",
1723 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1724}
1725
1726TEST(TemplateArgumentCountIs, Matches) {
1727 EXPECT_TRUE(
1728 matches("template<typename T> struct C {}; C<int> c;",
1729 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1730 EXPECT_TRUE(
1731 notMatches("template<typename T> struct C {}; C<int> c;",
1732 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1733
1734 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1735 templateSpecializationType(templateArgumentCountIs(1))));
1736 EXPECT_TRUE(
1737 notMatches("template<typename T> struct C {}; C<int> c;",
1738 templateSpecializationType(templateArgumentCountIs(2))));
1739}
1740
1741TEST(IsIntegral, Matches) {
1742 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1743 classTemplateSpecializationDecl(
1744 hasAnyTemplateArgument(isIntegral()))));
1745 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1746 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1747 templateArgument(isIntegral())))));
1748}
1749
1750TEST(RefersToIntegralType, Matches) {
1751 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1752 classTemplateSpecializationDecl(
1753 hasAnyTemplateArgument(refersToIntegralType(
1754 asString("int"))))));
1755 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1756 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1757 refersToIntegralType(asString("int"))))));
1758}
1759
1760TEST(EqualsIntegralValue, Matches) {
1761 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1762 classTemplateSpecializationDecl(
1763 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1764 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1765 classTemplateSpecializationDecl(
1766 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1767 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1768 classTemplateSpecializationDecl(
1769 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1770 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1771 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1772 equalsIntegralValue("0042")))));
1773}
1774
Daniel Jasper639522c2013-02-25 12:02:08 +00001775TEST(Matcher, MatchesAccessSpecDecls) {
1776 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1777 EXPECT_TRUE(
1778 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1779 EXPECT_TRUE(
1780 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1781 EXPECT_TRUE(
1782 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1783
1784 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1785}
1786
Aaron Ballman41143bb2015-07-24 12:35:41 +00001787TEST(Matcher, MatchesFinal) {
1788 EXPECT_TRUE(matches("class X final {};", recordDecl(isFinal())));
1789 EXPECT_TRUE(matches("class X { virtual void f() final; };",
1790 methodDecl(isFinal())));
1791 EXPECT_TRUE(notMatches("class X {};", recordDecl(isFinal())));
1792 EXPECT_TRUE(notMatches("class X { virtual void f(); };",
1793 methodDecl(isFinal())));
1794}
1795
Edwin Vane37ee1d72013-04-09 20:46:36 +00001796TEST(Matcher, MatchesVirtualMethod) {
1797 EXPECT_TRUE(matches("class X { virtual int f(); };",
1798 methodDecl(isVirtual(), hasName("::X::f"))));
1799 EXPECT_TRUE(notMatches("class X { int f(); };",
1800 methodDecl(isVirtual())));
1801}
1802
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001803TEST(Matcher, MatchesPureMethod) {
1804 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1805 methodDecl(isPure(), hasName("::X::f"))));
1806 EXPECT_TRUE(notMatches("class X { int f(); };",
1807 methodDecl(isPure())));
1808}
1809
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001810TEST(Matcher, MatchesConstMethod) {
1811 EXPECT_TRUE(matches("struct A { void foo() const; };",
1812 methodDecl(isConst())));
1813 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1814 methodDecl(isConst())));
1815}
1816
Edwin Vane37ee1d72013-04-09 20:46:36 +00001817TEST(Matcher, MatchesOverridingMethod) {
1818 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1819 "class Y : public X { int f(); };",
1820 methodDecl(isOverride(), hasName("::Y::f"))));
1821 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1822 "class Y : public X { int f(); };",
1823 methodDecl(isOverride(), hasName("::X::f"))));
1824 EXPECT_TRUE(notMatches("class X { int f(); }; "
1825 "class Y : public X { int f(); };",
1826 methodDecl(isOverride())));
1827 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1828 methodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001829 EXPECT_TRUE(
1830 matches("template <typename Base> struct Y : Base { void f() override;};",
1831 methodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001832}
1833
Manuel Klimek04616e42012-07-06 05:48:52 +00001834TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001835 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001836
1837 EXPECT_TRUE(
1838 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1839 EXPECT_TRUE(
1840 matches("class X { public: X(); }; void x() { X x = X(); }",
1841 Constructor));
1842 EXPECT_TRUE(
1843 matches("class X { public: X(int); }; void x() { X x = 0; }",
1844 Constructor));
1845 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1846}
1847
1848TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001849 StatementMatcher Constructor = constructExpr(
1850 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001851
1852 EXPECT_TRUE(
1853 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1854 Constructor));
1855 EXPECT_TRUE(
1856 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1857 Constructor));
1858 EXPECT_TRUE(
1859 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1860 Constructor));
1861 EXPECT_TRUE(
1862 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1863 Constructor));
1864
Daniel Jasper848cbe12012-09-18 13:09:13 +00001865 StatementMatcher WrongIndex = constructExpr(
1866 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001867 EXPECT_TRUE(
1868 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1869 WrongIndex));
1870}
1871
1872TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001873 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001874
1875 EXPECT_TRUE(
1876 matches("class X { public: X(int); }; void x() { X x(0); }",
1877 Constructor1Arg));
1878 EXPECT_TRUE(
1879 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1880 Constructor1Arg));
1881 EXPECT_TRUE(
1882 matches("class X { public: X(int); }; void x() { X x = 0; }",
1883 Constructor1Arg));
1884 EXPECT_TRUE(
1885 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1886 Constructor1Arg));
1887}
1888
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001889TEST(Matcher, ConstructorListInitialization) {
1890 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1891
1892 EXPECT_TRUE(
1893 matches("class X { public: X(int); }; void x() { X x{0}; }",
1894 ConstructorListInit));
1895 EXPECT_FALSE(
1896 matches("class X { public: X(int); }; void x() { X x(0); }",
1897 ConstructorListInit));
1898}
1899
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001900TEST(Matcher,ThisExpr) {
1901 EXPECT_TRUE(
1902 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1903 EXPECT_TRUE(
1904 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1905}
1906
Manuel Klimek04616e42012-07-06 05:48:52 +00001907TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001908 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001909
1910 std::string ClassString = "class string { public: string(); ~string(); }; ";
1911
1912 EXPECT_TRUE(
1913 matches(ClassString +
1914 "string GetStringByValue();"
1915 "void FunctionTakesString(string s);"
1916 "void run() { FunctionTakesString(GetStringByValue()); }",
1917 TempExpression));
1918
1919 EXPECT_TRUE(
1920 notMatches(ClassString +
1921 "string* GetStringPointer(); "
1922 "void FunctionTakesStringPtr(string* s);"
1923 "void run() {"
1924 " string* s = GetStringPointer();"
1925 " FunctionTakesStringPtr(GetStringPointer());"
1926 " FunctionTakesStringPtr(s);"
1927 "}",
1928 TempExpression));
1929
1930 EXPECT_TRUE(
1931 notMatches("class no_dtor {};"
1932 "no_dtor GetObjByValue();"
1933 "void ConsumeObj(no_dtor param);"
1934 "void run() { ConsumeObj(GetObjByValue()); }",
1935 TempExpression));
1936}
1937
Sam Panzer68a35af2012-08-24 22:04:44 +00001938TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1939 std::string ClassString =
1940 "class string { public: string(); int length(); }; ";
1941
1942 EXPECT_TRUE(
1943 matches(ClassString +
1944 "string GetStringByValue();"
1945 "void FunctionTakesString(string s);"
1946 "void run() { FunctionTakesString(GetStringByValue()); }",
1947 materializeTemporaryExpr()));
1948
1949 EXPECT_TRUE(
1950 notMatches(ClassString +
1951 "string* GetStringPointer(); "
1952 "void FunctionTakesStringPtr(string* s);"
1953 "void run() {"
1954 " string* s = GetStringPointer();"
1955 " FunctionTakesStringPtr(GetStringPointer());"
1956 " FunctionTakesStringPtr(s);"
1957 "}",
1958 materializeTemporaryExpr()));
1959
1960 EXPECT_TRUE(
1961 notMatches(ClassString +
1962 "string GetStringByValue();"
1963 "void run() { int k = GetStringByValue().length(); }",
1964 materializeTemporaryExpr()));
1965
1966 EXPECT_TRUE(
1967 notMatches(ClassString +
1968 "string GetStringByValue();"
1969 "void run() { GetStringByValue(); }",
1970 materializeTemporaryExpr()));
1971}
1972
Manuel Klimek04616e42012-07-06 05:48:52 +00001973TEST(ConstructorDeclaration, SimpleCase) {
1974 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001975 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001976 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001977 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001978}
1979
1980TEST(ConstructorDeclaration, IsImplicit) {
1981 // This one doesn't match because the constructor is not added by the
1982 // compiler (it is not needed).
1983 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001984 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001985 // The compiler added the implicit default constructor.
1986 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001987 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001988 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001989 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001990 // The compiler added an implicit assignment operator.
1991 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1992 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001993}
1994
Aaron Ballman1ca258e2015-08-05 12:11:30 +00001995TEST(ConstructorDeclaration, Kinds) {
1996 EXPECT_TRUE(matches("struct S { S(); };",
1997 constructorDecl(isDefaultConstructor())));
1998 EXPECT_TRUE(notMatches("struct S { S(); };",
1999 constructorDecl(isCopyConstructor())));
2000 EXPECT_TRUE(notMatches("struct S { S(); };",
2001 constructorDecl(isMoveConstructor())));
2002
2003 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
2004 constructorDecl(isDefaultConstructor())));
2005 EXPECT_TRUE(matches("struct S { S(const S&); };",
2006 constructorDecl(isCopyConstructor())));
2007 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
2008 constructorDecl(isMoveConstructor())));
2009
2010 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
2011 constructorDecl(isDefaultConstructor())));
2012 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
2013 constructorDecl(isCopyConstructor())));
2014 EXPECT_TRUE(matches("struct S { S(S&&); };",
2015 constructorDecl(isMoveConstructor())));
2016}
2017
Daniel Jasper1dad1832012-07-10 20:20:19 +00002018TEST(DestructorDeclaration, MatchesVirtualDestructor) {
2019 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002020 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002021}
2022
2023TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002024 EXPECT_TRUE(notMatches("class Foo {};",
2025 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002026}
2027
Manuel Klimek04616e42012-07-06 05:48:52 +00002028TEST(HasAnyConstructorInitializer, SimpleCase) {
2029 EXPECT_TRUE(notMatches(
2030 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002031 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002032 EXPECT_TRUE(matches(
2033 "class Foo {"
2034 " Foo() : foo_() { }"
2035 " int foo_;"
2036 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002037 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002038}
2039
2040TEST(HasAnyConstructorInitializer, ForField) {
2041 static const char Code[] =
2042 "class Baz { };"
2043 "class Foo {"
2044 " Foo() : foo_() { }"
2045 " Baz foo_;"
2046 " Baz bar_;"
2047 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002048 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
2049 forField(hasType(recordDecl(hasName("Baz"))))))));
2050 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002051 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002052 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
2053 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002054}
2055
2056TEST(HasAnyConstructorInitializer, WithInitializer) {
2057 static const char Code[] =
2058 "class Foo {"
2059 " Foo() : foo_(0) { }"
2060 " int foo_;"
2061 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002062 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002063 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002064 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002065 withInitializer(integerLiteral(equals(1)))))));
2066}
2067
2068TEST(HasAnyConstructorInitializer, IsWritten) {
2069 static const char Code[] =
2070 "struct Bar { Bar(){} };"
2071 "class Foo {"
2072 " Foo() : foo_() { }"
2073 " Bar foo_;"
2074 " Bar bar_;"
2075 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002076 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002077 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002078 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002079 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002080 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002081 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2082}
2083
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002084TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
2085 static const char Code[] =
2086 "struct B {};"
2087 "struct D : B {"
2088 " int I;"
2089 " D(int i) : I(i) {}"
2090 "};"
2091 "struct E : B {"
2092 " E() : B() {}"
2093 "};";
2094 EXPECT_TRUE(matches(Code, constructorDecl(allOf(
2095 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2096 hasName("E")))));
2097 EXPECT_TRUE(notMatches(Code, constructorDecl(allOf(
2098 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2099 hasName("D")))));
Aaron Ballmaned455d42015-08-11 20:42:00 +00002100 EXPECT_TRUE(matches(Code, constructorDecl(allOf(
2101 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2102 hasName("D")))));
2103 EXPECT_TRUE(notMatches(Code, constructorDecl(allOf(
2104 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2105 hasName("E")))));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002106}
2107
Manuel Klimek04616e42012-07-06 05:48:52 +00002108TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002109 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002110
2111 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2112 EXPECT_TRUE(
2113 matches("class X { public: X(); }; void x() { new X(); }", New));
2114 EXPECT_TRUE(
2115 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2116 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2117}
2118
2119TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002120 StatementMatcher New = constructExpr(
2121 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002122
2123 EXPECT_TRUE(
2124 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2125 New));
2126 EXPECT_TRUE(
2127 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2128 New));
2129 EXPECT_TRUE(
2130 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2131 New));
2132
Daniel Jasper848cbe12012-09-18 13:09:13 +00002133 StatementMatcher WrongIndex = constructExpr(
2134 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002135 EXPECT_TRUE(
2136 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2137 WrongIndex));
2138}
2139
2140TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002141 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002142
2143 EXPECT_TRUE(
2144 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2145 EXPECT_TRUE(
2146 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2147 New));
2148}
2149
Daniel Jasper1dad1832012-07-10 20:20:19 +00002150TEST(Matcher, DeleteExpression) {
2151 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002152 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002153}
2154
Manuel Klimek04616e42012-07-06 05:48:52 +00002155TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002156 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002157
2158 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2159 EXPECT_TRUE(
2160 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2161 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2162}
2163
2164TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002165 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002166 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2167 // wide string
2168 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2169 // with escaped characters
2170 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2171 // no matching -- though the data type is the same, there is no string literal
2172 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2173}
2174
2175TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002176 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002177 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2178 // wide character
2179 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2180 // wide character, Hex encoded, NOT MATCHED!
2181 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2182 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2183}
2184
2185TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002186 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002187 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2188 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2189 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2190 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2191
2192 // Non-matching cases (character literals, float and double)
2193 EXPECT_TRUE(notMatches("int i = L'a';",
2194 HasIntLiteral)); // this is actually a character
2195 // literal cast to int
2196 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2197 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2198 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2199}
2200
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002201TEST(Matcher, FloatLiterals) {
2202 StatementMatcher HasFloatLiteral = floatLiteral();
2203 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2204 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2205 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2206 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2207 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002208 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2209 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2210 EXPECT_TRUE(
2211 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002212
2213 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002214 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2215 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2216 EXPECT_TRUE(
2217 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002218}
2219
Daniel Jasper5901e472012-10-01 13:40:41 +00002220TEST(Matcher, NullPtrLiteral) {
2221 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2222}
2223
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002224TEST(Matcher, GNUNullExpr) {
2225 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2226}
2227
Daniel Jasper87c3d362012-09-20 14:12:57 +00002228TEST(Matcher, AsmStatement) {
2229 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2230}
2231
Manuel Klimek04616e42012-07-06 05:48:52 +00002232TEST(Matcher, Conditions) {
2233 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2234
2235 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2236 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2237 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2238 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2239 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2240}
2241
Manuel Klimek909b5c942014-05-27 10:04:12 +00002242TEST(IfStmt, ChildTraversalMatchers) {
2243 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2244 ifStmt(hasThen(boolLiteral(equals(true))))));
2245 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2246 ifStmt(hasThen(boolLiteral(equals(true))))));
2247 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2248 ifStmt(hasElse(boolLiteral(equals(true))))));
2249 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2250 ifStmt(hasElse(boolLiteral(equals(true))))));
2251}
2252
Manuel Klimek04616e42012-07-06 05:48:52 +00002253TEST(MatchBinaryOperator, HasOperatorName) {
2254 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2255
2256 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2257 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2258}
2259
2260TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2261 StatementMatcher OperatorTrueFalse =
2262 binaryOperator(hasLHS(boolLiteral(equals(true))),
2263 hasRHS(boolLiteral(equals(false))));
2264
2265 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2266 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2267 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2268}
2269
2270TEST(MatchBinaryOperator, HasEitherOperand) {
2271 StatementMatcher HasOperand =
2272 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2273
2274 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2275 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2276 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2277}
2278
2279TEST(Matcher, BinaryOperatorTypes) {
2280 // Integration test that verifies the AST provides all binary operators in
2281 // a way we expect.
2282 // FIXME: Operator ','
2283 EXPECT_TRUE(
2284 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2285 EXPECT_TRUE(
2286 matches("bool b; bool c = (b = true);",
2287 binaryOperator(hasOperatorName("="))));
2288 EXPECT_TRUE(
2289 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2290 EXPECT_TRUE(
2291 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2292 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2293 EXPECT_TRUE(
2294 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2295 EXPECT_TRUE(
2296 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2297 EXPECT_TRUE(
2298 matches("int i = 1; int j = (i <<= 2);",
2299 binaryOperator(hasOperatorName("<<="))));
2300 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2301 EXPECT_TRUE(
2302 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2303 EXPECT_TRUE(
2304 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2305 EXPECT_TRUE(
2306 matches("int i = 1; int j = (i >>= 2);",
2307 binaryOperator(hasOperatorName(">>="))));
2308 EXPECT_TRUE(
2309 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2310 EXPECT_TRUE(
2311 matches("int i = 42; int j = (i ^= 42);",
2312 binaryOperator(hasOperatorName("^="))));
2313 EXPECT_TRUE(
2314 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2315 EXPECT_TRUE(
2316 matches("int i = 42; int j = (i %= 42);",
2317 binaryOperator(hasOperatorName("%="))));
2318 EXPECT_TRUE(
2319 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2320 EXPECT_TRUE(
2321 matches("bool b = true && false;",
2322 binaryOperator(hasOperatorName("&&"))));
2323 EXPECT_TRUE(
2324 matches("bool b = true; bool c = (b &= false);",
2325 binaryOperator(hasOperatorName("&="))));
2326 EXPECT_TRUE(
2327 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2328 EXPECT_TRUE(
2329 matches("bool b = true || false;",
2330 binaryOperator(hasOperatorName("||"))));
2331 EXPECT_TRUE(
2332 matches("bool b = true; bool c = (b |= false);",
2333 binaryOperator(hasOperatorName("|="))));
2334 EXPECT_TRUE(
2335 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2336 EXPECT_TRUE(
2337 matches("int i = 42; int j = (i *= 23);",
2338 binaryOperator(hasOperatorName("*="))));
2339 EXPECT_TRUE(
2340 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2341 EXPECT_TRUE(
2342 matches("int i = 42; int j = (i /= 23);",
2343 binaryOperator(hasOperatorName("/="))));
2344 EXPECT_TRUE(
2345 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2346 EXPECT_TRUE(
2347 matches("int i = 42; int j = (i += 23);",
2348 binaryOperator(hasOperatorName("+="))));
2349 EXPECT_TRUE(
2350 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2351 EXPECT_TRUE(
2352 matches("int i = 42; int j = (i -= 23);",
2353 binaryOperator(hasOperatorName("-="))));
2354 EXPECT_TRUE(
2355 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2356 binaryOperator(hasOperatorName("->*"))));
2357 EXPECT_TRUE(
2358 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2359 binaryOperator(hasOperatorName(".*"))));
2360
2361 // Member expressions as operators are not supported in matches.
2362 EXPECT_TRUE(
2363 notMatches("struct A { void x(A *a) { a->x(this); } };",
2364 binaryOperator(hasOperatorName("->"))));
2365
2366 // Initializer assignments are not represented as operator equals.
2367 EXPECT_TRUE(
2368 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2369
2370 // Array indexing is not represented as operator.
2371 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2372
2373 // Overloaded operators do not match at all.
2374 EXPECT_TRUE(notMatches(
2375 "struct A { bool operator&&(const A &a) const { return false; } };"
2376 "void x() { A a, b; a && b; }",
2377 binaryOperator()));
2378}
2379
2380TEST(MatchUnaryOperator, HasOperatorName) {
2381 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2382
2383 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2384 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2385}
2386
2387TEST(MatchUnaryOperator, HasUnaryOperand) {
2388 StatementMatcher OperatorOnFalse =
2389 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2390
2391 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2392 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2393}
2394
2395TEST(Matcher, UnaryOperatorTypes) {
2396 // Integration test that verifies the AST provides all unary operators in
2397 // a way we expect.
2398 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2399 EXPECT_TRUE(
2400 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2401 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2402 EXPECT_TRUE(
2403 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2404 EXPECT_TRUE(
2405 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2406 EXPECT_TRUE(
2407 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2408 EXPECT_TRUE(
2409 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2410 EXPECT_TRUE(
2411 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2412 EXPECT_TRUE(
2413 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2414 EXPECT_TRUE(
2415 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2416
2417 // We don't match conversion operators.
2418 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2419
2420 // Function calls are not represented as operator.
2421 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2422
2423 // Overloaded operators do not match at all.
2424 // FIXME: We probably want to add that.
2425 EXPECT_TRUE(notMatches(
2426 "struct A { bool operator!() const { return false; } };"
2427 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2428}
2429
2430TEST(Matcher, ConditionalOperator) {
2431 StatementMatcher Conditional = conditionalOperator(
2432 hasCondition(boolLiteral(equals(true))),
2433 hasTrueExpression(boolLiteral(equals(false))));
2434
2435 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2436 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2437 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2438
2439 StatementMatcher ConditionalFalse = conditionalOperator(
2440 hasFalseExpression(boolLiteral(equals(false))));
2441
2442 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2443 EXPECT_TRUE(
2444 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2445}
2446
Daniel Jasper1dad1832012-07-10 20:20:19 +00002447TEST(ArraySubscriptMatchers, ArraySubscripts) {
2448 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2449 arraySubscriptExpr()));
2450 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2451 arraySubscriptExpr()));
2452}
2453
2454TEST(ArraySubscriptMatchers, ArrayIndex) {
2455 EXPECT_TRUE(matches(
2456 "int i[2]; void f() { i[1] = 1; }",
2457 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2458 EXPECT_TRUE(matches(
2459 "int i[2]; void f() { 1[i] = 1; }",
2460 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2461 EXPECT_TRUE(notMatches(
2462 "int i[2]; void f() { i[1] = 1; }",
2463 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2464}
2465
2466TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2467 EXPECT_TRUE(matches(
2468 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002469 arraySubscriptExpr(hasBase(implicitCastExpr(
2470 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002471}
2472
Manuel Klimek04616e42012-07-06 05:48:52 +00002473TEST(Matcher, HasNameSupportsNamespaces) {
2474 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002475 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002476 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002477 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002478 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002479 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002480 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002481 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002482 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002483 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002484 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002485 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002486 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002487 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002488 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002489 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002490 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002491 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002492 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002493 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002494 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002495 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002496 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002497 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002498}
2499
2500TEST(Matcher, HasNameSupportsOuterClasses) {
2501 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002502 matches("class A { class B { class C; }; };",
2503 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002504 EXPECT_TRUE(
2505 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002506 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002507 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002508 matches("class A { class B { class C; }; };",
2509 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002510 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002511 matches("class A { class B { class C; }; };",
2512 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002513 EXPECT_TRUE(
2514 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002515 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002516 EXPECT_TRUE(
2517 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002518 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002519 EXPECT_TRUE(
2520 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002521 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002522 EXPECT_TRUE(
2523 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002524 recordDecl(hasName("::C"))));
2525 EXPECT_TRUE(
2526 notMatches("class A { class B { class C; }; };",
2527 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002528 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002529 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002530 EXPECT_TRUE(
2531 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002532 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002533}
2534
2535TEST(Matcher, IsDefinition) {
2536 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002537 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002538 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2539 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2540
2541 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002542 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002543 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2544 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2545
2546 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002547 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002548 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2549 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2550}
2551
2552TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002553 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002554 ofClass(hasName("X")))));
2555
2556 EXPECT_TRUE(
2557 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2558 EXPECT_TRUE(
2559 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2560 Constructor));
2561 EXPECT_TRUE(
2562 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2563 Constructor));
2564}
2565
2566TEST(Matcher, VisitsTemplateInstantiations) {
2567 EXPECT_TRUE(matches(
2568 "class A { public: void x(); };"
2569 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002570 "void f() { B<A> b; b.y(); }",
2571 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002572
2573 EXPECT_TRUE(matches(
2574 "class A { public: void x(); };"
2575 "class C {"
2576 " public:"
2577 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2578 "};"
2579 "void f() {"
2580 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002581 "}",
2582 recordDecl(hasName("C"),
2583 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002584}
2585
Daniel Jasper1dad1832012-07-10 20:20:19 +00002586TEST(Matcher, HandlesNullQualTypes) {
2587 // FIXME: Add a Type matcher so we can replace uses of this
2588 // variable with Type(True())
2589 const TypeMatcher AnyType = anything();
2590
2591 // We don't really care whether this matcher succeeds; we're testing that
2592 // it completes without crashing.
2593 EXPECT_TRUE(matches(
2594 "struct A { };"
2595 "template <typename T>"
2596 "void f(T t) {"
2597 " T local_t(t /* this becomes a null QualType in the AST */);"
2598 "}"
2599 "void g() {"
2600 " f(0);"
2601 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002602 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002603 anyOf(
2604 TypeMatcher(hasDeclaration(anything())),
2605 pointsTo(AnyType),
2606 references(AnyType)
2607 // Other QualType matchers should go here.
2608 ))))));
2609}
2610
Manuel Klimek04616e42012-07-06 05:48:52 +00002611// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002612AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002613 // Make sure all special variables are used: node, match_finder,
2614 // bound_nodes_builder, and the parameter named 'AMatcher'.
2615 return AMatcher.matches(Node, Finder, Builder);
2616}
2617
2618TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002619 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002620
2621 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002622 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002623
2624 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002625 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002626
2627 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002628 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002629}
2630
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002631AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2632 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2633 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002634 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002635 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002636 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2637 ASTMatchFinder::BK_First);
2638}
2639
2640TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002641 DeclarationMatcher HasClassB =
2642 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002643
2644 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002645 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002646
2647 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002648 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002649
2650 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002651 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002652
2653 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002654 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002655
2656 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2657}
2658
2659TEST(For, FindsForLoops) {
2660 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2661 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002662 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2663 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002664 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002665}
2666
Daniel Jasper4e566c42012-07-12 08:50:38 +00002667TEST(For, ForLoopInternals) {
2668 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2669 forStmt(hasCondition(anything()))));
2670 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2671 forStmt(hasLoopInit(anything()))));
2672}
2673
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002674TEST(For, ForRangeLoopInternals) {
2675 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2676 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002677 EXPECT_TRUE(matches(
2678 "void f(){ int a[] {1, 2}; for (int i : a); }",
2679 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002680}
2681
Daniel Jasper4e566c42012-07-12 08:50:38 +00002682TEST(For, NegativeForLoopInternals) {
2683 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002684 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002685 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2686 forStmt(hasLoopInit(anything()))));
2687}
2688
Manuel Klimek04616e42012-07-06 05:48:52 +00002689TEST(For, ReportsNoFalsePositives) {
2690 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2691 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2692}
2693
2694TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002695 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2696 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2697 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002698}
2699
2700TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2701 // It's not a compound statement just because there's "{}" in the source
2702 // text. This is an AST search, not grep.
2703 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002704 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002705 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002706 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002707}
2708
Daniel Jasper4e566c42012-07-12 08:50:38 +00002709TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002710 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002711 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002712 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002713 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002714 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002715 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002716 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002717 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002718 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2719 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002720}
2721
2722TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2723 // The simplest case: every compound statement is in a function
2724 // definition, and the function body itself must be a compound
2725 // statement.
2726 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002727 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002728}
2729
2730TEST(HasAnySubstatement, IsNotRecursive) {
2731 // It's really "has any immediate substatement".
2732 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002733 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002734}
2735
2736TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2737 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002738 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002739}
2740
2741TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2742 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002743 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002744}
2745
2746TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2747 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002748 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002749 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002750 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002751}
2752
2753TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2754 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002755 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002756 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002757 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002758 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002759 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002760}
2761
2762TEST(StatementCountIs, WorksWithMultipleStatements) {
2763 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002764 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002765}
2766
2767TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2768 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002769 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002770 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002771 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002772 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002773 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002774 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002775 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002776}
2777
2778TEST(Member, WorksInSimplestCase) {
2779 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002780 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002781}
2782
2783TEST(Member, DoesNotMatchTheBaseExpression) {
2784 // Don't pick out the wrong part of the member expression, this should
2785 // be checking the member (name) only.
2786 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002787 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002788}
2789
2790TEST(Member, MatchesInMemberFunctionCall) {
2791 EXPECT_TRUE(matches("void f() {"
2792 " struct { void first() {}; } s;"
2793 " s.first();"
2794 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002795 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002796}
2797
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002798TEST(Member, MatchesMember) {
2799 EXPECT_TRUE(matches(
2800 "struct A { int i; }; void f() { A a; a.i = 2; }",
2801 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2802 EXPECT_TRUE(notMatches(
2803 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2804 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2805}
2806
Daniel Jasper639522c2013-02-25 12:02:08 +00002807TEST(Member, UnderstandsAccess) {
2808 EXPECT_TRUE(matches(
2809 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2810 EXPECT_TRUE(notMatches(
2811 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2812 EXPECT_TRUE(notMatches(
2813 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2814
2815 EXPECT_TRUE(notMatches(
2816 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2817 EXPECT_TRUE(notMatches(
2818 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2819 EXPECT_TRUE(matches(
2820 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2821
2822 EXPECT_TRUE(notMatches(
2823 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2824 EXPECT_TRUE(matches("class A { protected: int i; };",
2825 fieldDecl(isProtected(), hasName("i"))));
2826 EXPECT_TRUE(notMatches(
2827 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2828
2829 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2830 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2831 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2832 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2833}
2834
Dmitri Gribenko06963042012-08-18 00:29:27 +00002835TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002836 // Fails in C++11 mode
2837 EXPECT_TRUE(matchesConditionally(
2838 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2839 "class X { void *operator new(std::size_t); };",
2840 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002841
2842 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002843 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002844
Daniel Jasper5901e472012-10-01 13:40:41 +00002845 // Fails in C++11 mode
2846 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002847 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2848 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002849 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002850}
2851
Manuel Klimek04616e42012-07-06 05:48:52 +00002852TEST(HasObjectExpression, DoesNotMatchMember) {
2853 EXPECT_TRUE(notMatches(
2854 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002855 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002856}
2857
2858TEST(HasObjectExpression, MatchesBaseOfVariable) {
2859 EXPECT_TRUE(matches(
2860 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002861 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002862 EXPECT_TRUE(matches(
2863 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002864 memberExpr(hasObjectExpression(
2865 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002866}
2867
2868TEST(HasObjectExpression,
2869 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2870 EXPECT_TRUE(matches(
2871 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002872 memberExpr(hasObjectExpression(
2873 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002874 EXPECT_TRUE(matches(
2875 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002876 memberExpr(hasObjectExpression(
2877 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002878}
2879
2880TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002881 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2882 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2883 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2884 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002885}
2886
2887TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002888 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002889}
2890
2891TEST(IsConstQualified, MatchesConstInt) {
2892 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002893 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002894}
2895
2896TEST(IsConstQualified, MatchesConstPointer) {
2897 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002898 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002899}
2900
2901TEST(IsConstQualified, MatchesThroughTypedef) {
2902 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002903 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002904 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002905 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002906}
2907
2908TEST(IsConstQualified, DoesNotMatchInappropriately) {
2909 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002910 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002911 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002912 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002913}
2914
Sam Panzer80c13772012-08-16 16:58:10 +00002915TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002916 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2917 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2918 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2919 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002920}
2921TEST(CastExpression, MatchesImplicitCasts) {
2922 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002923 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002924 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002925 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002926}
2927
2928TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002929 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2930 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2931 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2932 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002933}
2934
Manuel Klimek04616e42012-07-06 05:48:52 +00002935TEST(ReinterpretCast, MatchesSimpleCase) {
2936 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002937 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002938}
2939
2940TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002941 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002942 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002943 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002944 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002945 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002946 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2947 "B b;"
2948 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002949 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002950}
2951
2952TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002953 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002954 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002955 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002956}
2957
2958TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002959 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002960 EXPECT_TRUE(
2961 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002962 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002963 EXPECT_TRUE(
2964 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002965 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002966}
2967
2968TEST(DynamicCast, MatchesSimpleCase) {
2969 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2970 "B b;"
2971 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002972 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002973}
2974
2975TEST(StaticCast, MatchesSimpleCase) {
2976 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002977 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002978}
2979
2980TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002981 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002982 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002983 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002984 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002985 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002986 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2987 "B b;"
2988 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002989 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002990}
2991
Daniel Jasper417f7762012-09-18 13:36:17 +00002992TEST(CStyleCast, MatchesSimpleCase) {
2993 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2994}
2995
2996TEST(CStyleCast, DoesNotMatchOtherCasts) {
2997 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2998 "char q, *r = const_cast<char*>(&q);"
2999 "void* s = reinterpret_cast<char*>(&s);"
3000 "struct B { virtual ~B() {} }; struct D : B {};"
3001 "B b;"
3002 "D* t = dynamic_cast<D*>(&b);",
3003 cStyleCastExpr()));
3004}
3005
Manuel Klimek04616e42012-07-06 05:48:52 +00003006TEST(HasDestinationType, MatchesSimpleCase) {
3007 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003008 staticCastExpr(hasDestinationType(
3009 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003010}
3011
Sam Panzer80c13772012-08-16 16:58:10 +00003012TEST(HasImplicitDestinationType, MatchesSimpleCase) {
3013 // This test creates an implicit const cast.
3014 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003015 implicitCastExpr(
3016 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003017 // This test creates an implicit array-to-pointer cast.
3018 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003019 implicitCastExpr(hasImplicitDestinationType(
3020 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003021}
3022
3023TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
3024 // This test creates an implicit cast from int to char.
3025 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003026 implicitCastExpr(hasImplicitDestinationType(
3027 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003028 // This test creates an implicit array-to-pointer cast.
3029 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003030 implicitCastExpr(hasImplicitDestinationType(
3031 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003032}
3033
3034TEST(ImplicitCast, MatchesSimpleCase) {
3035 // This test creates an implicit const cast.
3036 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003037 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003038 // This test creates an implicit cast from int to char.
3039 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003040 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003041 // This test creates an implicit array-to-pointer cast.
3042 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003043 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003044}
3045
3046TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003047 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00003048 // are present, and that it ignores explicit and paren casts.
3049
3050 // These two test cases have no casts.
3051 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003052 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003053 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003054 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003055
3056 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003057 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003058 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003059 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003060
3061 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003062 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003063}
3064
3065TEST(IgnoringImpCasts, MatchesImpCasts) {
3066 // This test checks that ignoringImpCasts matches when implicit casts are
3067 // present and its inner matcher alone does not match.
3068 // Note that this test creates an implicit const cast.
3069 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003070 varDecl(hasInitializer(ignoringImpCasts(
3071 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003072 // This test creates an implict cast from int to char.
3073 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003074 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003075 integerLiteral(equals(0)))))));
3076}
3077
3078TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3079 // These tests verify that ignoringImpCasts does not match if the inner
3080 // matcher does not match.
3081 // Note that the first test creates an implicit const cast.
3082 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003083 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003084 unless(anything()))))));
3085 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003086 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003087 unless(anything()))))));
3088
3089 // These tests verify that ignoringImplictCasts does not look through explicit
3090 // casts or parentheses.
3091 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003092 varDecl(hasInitializer(ignoringImpCasts(
3093 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003094 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003095 varDecl(hasInitializer(ignoringImpCasts(
3096 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003097 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003098 varDecl(hasInitializer(ignoringImpCasts(
3099 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003100 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003101 varDecl(hasInitializer(ignoringImpCasts(
3102 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003103}
3104
3105TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3106 // This test verifies that expressions that do not have implicit casts
3107 // still match the inner matcher.
3108 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003109 varDecl(hasInitializer(ignoringImpCasts(
3110 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003111}
3112
3113TEST(IgnoringParenCasts, MatchesParenCasts) {
3114 // This test checks that ignoringParenCasts matches when parentheses and/or
3115 // casts are present and its inner matcher alone does not match.
3116 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003117 varDecl(hasInitializer(ignoringParenCasts(
3118 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003119 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003120 varDecl(hasInitializer(ignoringParenCasts(
3121 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003122
3123 // This test creates an implict cast from int to char in addition to the
3124 // parentheses.
3125 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003126 varDecl(hasInitializer(ignoringParenCasts(
3127 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003128
3129 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003130 varDecl(hasInitializer(ignoringParenCasts(
3131 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003132 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003133 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003134 integerLiteral(equals(0)))))));
3135}
3136
3137TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3138 // This test verifies that expressions that do not have any casts still match.
3139 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003140 varDecl(hasInitializer(ignoringParenCasts(
3141 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003142}
3143
3144TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3145 // These tests verify that ignoringImpCasts does not match if the inner
3146 // matcher does not match.
3147 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003148 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003149 unless(anything()))))));
3150
3151 // This test creates an implicit cast from int to char in addition to the
3152 // parentheses.
3153 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003154 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003155 unless(anything()))))));
3156
3157 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003158 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003159 unless(anything()))))));
3160}
3161
3162TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3163 // This test checks that ignoringParenAndImpCasts matches when
3164 // parentheses and/or implicit casts are present and its inner matcher alone
3165 // does not match.
3166 // Note that this test creates an implicit const cast.
3167 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003168 varDecl(hasInitializer(ignoringParenImpCasts(
3169 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003170 // This test creates an implicit cast from int to char.
3171 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003172 varDecl(hasInitializer(ignoringParenImpCasts(
3173 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003174}
3175
3176TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3177 // This test verifies that expressions that do not have parentheses or
3178 // implicit casts still match.
3179 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003180 varDecl(hasInitializer(ignoringParenImpCasts(
3181 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003182 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003183 varDecl(hasInitializer(ignoringParenImpCasts(
3184 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003185}
3186
3187TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3188 // These tests verify that ignoringParenImpCasts does not match if
3189 // the inner matcher does not match.
3190 // This test creates an implicit cast.
3191 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003192 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003193 unless(anything()))))));
3194 // These tests verify that ignoringParenAndImplictCasts does not look
3195 // through explicit casts.
3196 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003197 varDecl(hasInitializer(ignoringParenImpCasts(
3198 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003199 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003200 varDecl(hasInitializer(ignoringParenImpCasts(
3201 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003202 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003203 varDecl(hasInitializer(ignoringParenImpCasts(
3204 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003205}
3206
Manuel Klimeke9235692012-07-25 10:02:02 +00003207TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003208 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3209 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003210 implicitCastExpr(
3211 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003212}
3213
Manuel Klimeke9235692012-07-25 10:02:02 +00003214TEST(HasSourceExpression, MatchesExplicitCasts) {
3215 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003216 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003217 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003218 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003219}
3220
Manuel Klimek04616e42012-07-06 05:48:52 +00003221TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003222 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003223}
3224
3225TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003226 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003227}
3228
3229TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003230 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003231}
3232
3233TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003234 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003235}
3236
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003237TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3238 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3239 "const Foo f = Foo();",
3240 varDecl(hasInitializer(exprWithCleanups()))));
3241 EXPECT_FALSE(matches("struct Foo { };"
3242 "const Foo f = Foo();",
3243 varDecl(hasInitializer(exprWithCleanups()))));
3244}
3245
Daniel Jasper1dad1832012-07-10 20:20:19 +00003246TEST(InitListExpression, MatchesInitListExpression) {
3247 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3248 initListExpr(hasType(asString("int [2]")))));
3249 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003250 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003251 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3252 "void f();"
3253 "S s[1] = { &f };",
3254 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003255 EXPECT_TRUE(
3256 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003257}
3258
3259TEST(UsingDeclaration, MatchesUsingDeclarations) {
3260 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3261 usingDecl()));
3262}
3263
3264TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3265 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3266 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3267}
3268
3269TEST(UsingDeclaration, MatchesSpecificTarget) {
3270 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3271 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003272 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003273 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3274 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003275 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003276}
3277
3278TEST(UsingDeclaration, ThroughUsingDeclaration) {
3279 EXPECT_TRUE(matches(
3280 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003281 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003282 EXPECT_TRUE(notMatches(
3283 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003284 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003285}
3286
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003287TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3288 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3289 usingDirectiveDecl()));
3290 EXPECT_FALSE(
3291 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3292}
3293
Sam Panzerd624bfb2012-08-16 17:20:59 +00003294TEST(SingleDecl, IsSingleDecl) {
3295 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003296 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003297 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3298 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3299 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3300 SingleDeclStmt));
3301}
3302
3303TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003304 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003305
3306 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003307 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003308 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003309 declStmt(containsDeclaration(0, MatchesInit),
3310 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003311 unsigned WrongIndex = 42;
3312 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003313 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003314 MatchesInit))));
3315}
3316
3317TEST(DeclCount, DeclCountIsCorrect) {
3318 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003319 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003320 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003321 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003322 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003323 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003324}
3325
Manuel Klimek04616e42012-07-06 05:48:52 +00003326TEST(While, MatchesWhileLoops) {
3327 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3328 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3329 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3330}
3331
3332TEST(Do, MatchesDoLoops) {
3333 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3334 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3335}
3336
3337TEST(Do, DoesNotMatchWhileLoops) {
3338 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3339}
3340
3341TEST(SwitchCase, MatchesCase) {
3342 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3343 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3344 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3345 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3346}
3347
Daniel Jasper87c3d362012-09-20 14:12:57 +00003348TEST(SwitchCase, MatchesSwitch) {
3349 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3350 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3351 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3352 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3353}
3354
Peter Collingbourne3154a102013-05-10 11:52:02 +00003355TEST(SwitchCase, MatchesEachCase) {
3356 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3357 switchStmt(forEachSwitchCase(caseStmt()))));
3358 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3359 switchStmt(forEachSwitchCase(caseStmt()))));
3360 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3361 switchStmt(forEachSwitchCase(caseStmt()))));
3362 EXPECT_TRUE(notMatches(
3363 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3364 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3365 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3366 switchStmt(forEachSwitchCase(
3367 caseStmt(hasCaseConstant(integerLiteral()))))));
3368 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3369 switchStmt(forEachSwitchCase(
3370 caseStmt(hasCaseConstant(integerLiteral()))))));
3371 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3372 switchStmt(forEachSwitchCase(
3373 caseStmt(hasCaseConstant(integerLiteral()))))));
3374 EXPECT_TRUE(matchAndVerifyResultTrue(
3375 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3376 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3377 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3378}
3379
Manuel Klimekba46fc02013-07-19 11:50:54 +00003380TEST(ForEachConstructorInitializer, MatchesInitializers) {
3381 EXPECT_TRUE(matches(
3382 "struct X { X() : i(42), j(42) {} int i, j; };",
3383 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3384}
3385
Daniel Jasper87c3d362012-09-20 14:12:57 +00003386TEST(ExceptionHandling, SimpleCases) {
3387 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3388 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3389 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3390 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3391 throwExpr()));
3392 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3393 throwExpr()));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003394 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
3395 catchStmt(isCatchAll())));
3396 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
3397 catchStmt(isCatchAll())));
Aaron Ballman39918462015-07-15 17:11:21 +00003398 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3399 varDecl(isExceptionVariable())));
3400 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3401 varDecl(isExceptionVariable())));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003402}
3403
Manuel Klimek04616e42012-07-06 05:48:52 +00003404TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3405 EXPECT_TRUE(notMatches(
3406 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003407 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003408 EXPECT_TRUE(notMatches(
3409 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003410 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003411}
3412
3413TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3414 EXPECT_TRUE(matches(
3415 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003416 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003417}
3418
3419TEST(ForEach, BindsOneNode) {
3420 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003421 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003422 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003423}
3424
3425TEST(ForEach, BindsMultipleNodes) {
3426 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003427 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003428 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003429}
3430
3431TEST(ForEach, BindsRecursiveCombinations) {
3432 EXPECT_TRUE(matchAndVerifyResultTrue(
3433 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003434 recordDecl(hasName("C"),
3435 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003436 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003437}
3438
3439TEST(ForEachDescendant, BindsOneNode) {
3440 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003441 recordDecl(hasName("C"),
3442 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003443 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003444}
3445
Daniel Jasper94a56852012-11-16 18:39:22 +00003446TEST(ForEachDescendant, NestedForEachDescendant) {
3447 DeclarationMatcher m = recordDecl(
3448 isDefinition(), decl().bind("x"), hasName("C"));
3449 EXPECT_TRUE(matchAndVerifyResultTrue(
3450 "class A { class B { class C {}; }; };",
3451 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3452 new VerifyIdIsBoundTo<Decl>("x", "C")));
3453
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003454 // Check that a partial match of 'm' that binds 'x' in the
3455 // first part of anyOf(m, anything()) will not overwrite the
3456 // binding created by the earlier binding in the hasDescendant.
3457 EXPECT_TRUE(matchAndVerifyResultTrue(
3458 "class A { class B { class C {}; }; };",
3459 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3460 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003461}
3462
Manuel Klimek04616e42012-07-06 05:48:52 +00003463TEST(ForEachDescendant, BindsMultipleNodes) {
3464 EXPECT_TRUE(matchAndVerifyResultTrue(
3465 "class C { class D { int x; int y; }; "
3466 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003467 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003468 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003469}
3470
3471TEST(ForEachDescendant, BindsRecursiveCombinations) {
3472 EXPECT_TRUE(matchAndVerifyResultTrue(
3473 "class C { class D { "
3474 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003475 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3476 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003477 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003478}
3479
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003480TEST(ForEachDescendant, BindsCombinations) {
3481 EXPECT_TRUE(matchAndVerifyResultTrue(
3482 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3483 "(true) {} }",
3484 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3485 forEachDescendant(whileStmt().bind("while"))),
3486 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3487}
3488
3489TEST(Has, DoesNotDeleteBindings) {
3490 EXPECT_TRUE(matchAndVerifyResultTrue(
3491 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3492 new VerifyIdIsBoundTo<Decl>("x", 1)));
3493}
3494
3495TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3496 // Those matchers cover all the cases where an inner matcher is called
3497 // and there is not a 1:1 relationship between the match of the outer
3498 // matcher and the match of the inner matcher.
3499 // The pattern to look for is:
3500 // ... return InnerMatcher.matches(...); ...
3501 // In which case no special handling is needed.
3502 //
3503 // On the other hand, if there are multiple alternative matches
3504 // (for example forEach*) or matches might be discarded (for example has*)
3505 // the implementation must make sure that the discarded matches do not
3506 // affect the bindings.
3507 // When new such matchers are added, add a test here that:
3508 // - matches a simple node, and binds it as the first thing in the matcher:
3509 // recordDecl(decl().bind("x"), hasName("X")))
3510 // - uses the matcher under test afterwards in a way that not the first
3511 // alternative is matched; for anyOf, that means the first branch
3512 // would need to return false; for hasAncestor, it means that not
3513 // the direct parent matches the inner matcher.
3514
3515 EXPECT_TRUE(matchAndVerifyResultTrue(
3516 "class X { int y; };",
3517 recordDecl(
3518 recordDecl().bind("x"), hasName("::X"),
3519 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3520 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3521 EXPECT_TRUE(matchAndVerifyResultTrue(
3522 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3523 anyOf(unless(anything()), anything())),
3524 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3525 EXPECT_TRUE(matchAndVerifyResultTrue(
3526 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3527 classTemplateSpecializationDecl(
3528 decl().bind("x"),
3529 hasAnyTemplateArgument(refersToType(asString("int")))),
3530 new VerifyIdIsBoundTo<Decl>("x", 1)));
3531 EXPECT_TRUE(matchAndVerifyResultTrue(
3532 "class X { void f(); void g(); };",
3533 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3534 new VerifyIdIsBoundTo<Decl>("x", 1)));
3535 EXPECT_TRUE(matchAndVerifyResultTrue(
3536 "class X { X() : a(1), b(2) {} double a; int b; };",
3537 recordDecl(decl().bind("x"),
3538 has(constructorDecl(
3539 hasAnyConstructorInitializer(forField(hasName("b")))))),
3540 new VerifyIdIsBoundTo<Decl>("x", 1)));
3541 EXPECT_TRUE(matchAndVerifyResultTrue(
3542 "void x(int, int) { x(0, 42); }",
3543 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3544 new VerifyIdIsBoundTo<Expr>("x", 1)));
3545 EXPECT_TRUE(matchAndVerifyResultTrue(
3546 "void x(int, int y) {}",
3547 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3548 new VerifyIdIsBoundTo<Decl>("x", 1)));
3549 EXPECT_TRUE(matchAndVerifyResultTrue(
3550 "void x() { return; if (true) {} }",
3551 functionDecl(decl().bind("x"),
3552 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3553 new VerifyIdIsBoundTo<Decl>("x", 1)));
3554 EXPECT_TRUE(matchAndVerifyResultTrue(
3555 "namespace X { void b(int); void b(); }"
3556 "using X::b;",
3557 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3558 functionDecl(parameterCountIs(1))))),
3559 new VerifyIdIsBoundTo<Decl>("x", 1)));
3560 EXPECT_TRUE(matchAndVerifyResultTrue(
3561 "class A{}; class B{}; class C : B, A {};",
3562 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3563 new VerifyIdIsBoundTo<Decl>("x", 1)));
3564 EXPECT_TRUE(matchAndVerifyResultTrue(
3565 "class A{}; typedef A B; typedef A C; typedef A D;"
3566 "class E : A {};",
3567 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3568 new VerifyIdIsBoundTo<Decl>("x", 1)));
3569 EXPECT_TRUE(matchAndVerifyResultTrue(
3570 "class A { class B { void f() {} }; };",
3571 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3572 new VerifyIdIsBoundTo<Decl>("x", 1)));
3573 EXPECT_TRUE(matchAndVerifyResultTrue(
3574 "template <typename T> struct A { struct B {"
3575 " void f() { if(true) {} }"
3576 "}; };"
3577 "void t() { A<int>::B b; b.f(); }",
3578 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3579 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3580 EXPECT_TRUE(matchAndVerifyResultTrue(
3581 "class A {};",
3582 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3583 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003584 EXPECT_TRUE(matchAndVerifyResultTrue(
3585 "class A { A() : s(), i(42) {} const char *s; int i; };",
3586 constructorDecl(hasName("::A::A"), decl().bind("x"),
3587 forEachConstructorInitializer(forField(hasName("i")))),
3588 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003589}
3590
Daniel Jasper33806cd2012-11-11 22:14:55 +00003591TEST(ForEachDescendant, BindsCorrectNodes) {
3592 EXPECT_TRUE(matchAndVerifyResultTrue(
3593 "class C { void f(); int i; };",
3594 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3595 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3596 EXPECT_TRUE(matchAndVerifyResultTrue(
3597 "class C { void f() {} int i; };",
3598 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3599 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3600}
3601
Manuel Klimekabf43712013-02-04 10:59:20 +00003602TEST(FindAll, BindsNodeOnMatch) {
3603 EXPECT_TRUE(matchAndVerifyResultTrue(
3604 "class A {};",
3605 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3606 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3607}
3608
3609TEST(FindAll, BindsDescendantNodeOnMatch) {
3610 EXPECT_TRUE(matchAndVerifyResultTrue(
3611 "class A { int a; int b; };",
3612 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3613 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3614}
3615
3616TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3617 EXPECT_TRUE(matchAndVerifyResultTrue(
3618 "class A { int a; int b; };",
3619 recordDecl(hasName("::A"),
3620 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3621 fieldDecl().bind("v"))))),
3622 new VerifyIdIsBoundTo<Decl>("v", 3)));
3623
3624 EXPECT_TRUE(matchAndVerifyResultTrue(
3625 "class A { class B {}; class C {}; };",
3626 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3627 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3628}
3629
Manuel Klimek88b95872013-02-04 09:42:38 +00003630TEST(EachOf, TriggersForEachMatch) {
3631 EXPECT_TRUE(matchAndVerifyResultTrue(
3632 "class A { int a; int b; };",
3633 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3634 has(fieldDecl(hasName("b")).bind("v")))),
3635 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3636}
3637
3638TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3639 EXPECT_TRUE(matchAndVerifyResultTrue(
3640 "class A { int a; int c; };",
3641 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3642 has(fieldDecl(hasName("b")).bind("v")))),
3643 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3644 EXPECT_TRUE(matchAndVerifyResultTrue(
3645 "class A { int c; int b; };",
3646 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3647 has(fieldDecl(hasName("b")).bind("v")))),
3648 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3649 EXPECT_TRUE(notMatches(
3650 "class A { int c; int d; };",
3651 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3652 has(fieldDecl(hasName("b")).bind("v"))))));
3653}
Manuel Klimek04616e42012-07-06 05:48:52 +00003654
3655TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3656 // Make sure that we can both match the class by name (::X) and by the type
3657 // the template was instantiated with (via a field).
3658
3659 EXPECT_TRUE(matches(
3660 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003661 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003662
3663 EXPECT_TRUE(matches(
3664 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003665 recordDecl(isTemplateInstantiation(), hasDescendant(
3666 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003667}
3668
3669TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3670 EXPECT_TRUE(matches(
3671 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003672 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003673 isTemplateInstantiation())));
3674}
3675
3676TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3677 EXPECT_TRUE(matches(
3678 "template <typename T> class X { T t; }; class A {};"
3679 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003680 recordDecl(isTemplateInstantiation(), hasDescendant(
3681 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003682}
3683
3684TEST(IsTemplateInstantiation,
3685 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3686 EXPECT_TRUE(matches(
3687 "template <typename T> class X {};"
3688 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003689 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003690}
3691
3692TEST(IsTemplateInstantiation,
3693 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3694 EXPECT_TRUE(matches(
3695 "class A {};"
3696 "class X {"
3697 " template <typename U> class Y { U u; };"
3698 " Y<A> y;"
3699 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003700 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003701}
3702
3703TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3704 // FIXME: Figure out whether this makes sense. It doesn't affect the
3705 // normal use case as long as the uppermost instantiation always is marked
3706 // as template instantiation, but it might be confusing as a predicate.
3707 EXPECT_TRUE(matches(
3708 "class A {};"
3709 "template <typename T> class X {"
3710 " template <typename U> class Y { U u; };"
3711 " Y<T> y;"
3712 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003713 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003714}
3715
3716TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3717 EXPECT_TRUE(notMatches(
3718 "template <typename T> class X {}; class A {};"
3719 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003720 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003721}
3722
3723TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3724 EXPECT_TRUE(notMatches(
3725 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003726 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003727}
3728
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003729TEST(IsInstantiated, MatchesInstantiation) {
3730 EXPECT_TRUE(
3731 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3732 recordDecl(isInstantiated())));
3733}
3734
3735TEST(IsInstantiated, NotMatchesDefinition) {
3736 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3737 recordDecl(isInstantiated())));
3738}
3739
3740TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3741 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3742 "class Y { A<int> a; }; Y y;",
3743 declStmt(isInTemplateInstantiation())));
3744}
3745
3746TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3747 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3748 declStmt(isInTemplateInstantiation())));
3749}
3750
3751TEST(IsInstantiated, MatchesFunctionInstantiation) {
3752 EXPECT_TRUE(
3753 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3754 functionDecl(isInstantiated())));
3755}
3756
3757TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3758 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3759 varDecl(isInstantiated())));
3760}
3761
3762TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3763 EXPECT_TRUE(
3764 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3765 declStmt(isInTemplateInstantiation())));
3766}
3767
3768TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3769 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3770 declStmt(isInTemplateInstantiation())));
3771}
3772
3773TEST(IsInTemplateInstantiation, Sharing) {
3774 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3775 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3776 // and makes the matcher behave in non-obvious ways.
3777 EXPECT_TRUE(notMatches(
3778 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3779 Matcher));
3780 EXPECT_TRUE(matches(
3781 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3782 Matcher));
3783}
3784
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003785TEST(IsExplicitTemplateSpecialization,
3786 DoesNotMatchPrimaryTemplate) {
3787 EXPECT_TRUE(notMatches(
3788 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003789 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003790 EXPECT_TRUE(notMatches(
3791 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003792 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003793}
3794
3795TEST(IsExplicitTemplateSpecialization,
3796 DoesNotMatchExplicitTemplateInstantiations) {
3797 EXPECT_TRUE(notMatches(
3798 "template <typename T> class X {};"
3799 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003800 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003801 EXPECT_TRUE(notMatches(
3802 "template <typename T> void f(T t) {}"
3803 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003804 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003805}
3806
3807TEST(IsExplicitTemplateSpecialization,
3808 DoesNotMatchImplicitTemplateInstantiations) {
3809 EXPECT_TRUE(notMatches(
3810 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003811 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003812 EXPECT_TRUE(notMatches(
3813 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003814 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003815}
3816
3817TEST(IsExplicitTemplateSpecialization,
3818 MatchesExplicitTemplateSpecializations) {
3819 EXPECT_TRUE(matches(
3820 "template <typename T> class X {};"
3821 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003822 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003823 EXPECT_TRUE(matches(
3824 "template <typename T> void f(T t) {}"
3825 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003826 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003827}
3828
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003829TEST(HasAncenstor, MatchesDeclarationAncestors) {
3830 EXPECT_TRUE(matches(
3831 "class A { class B { class C {}; }; };",
3832 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3833}
3834
3835TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3836 EXPECT_TRUE(notMatches(
3837 "class A { class B { class C {}; }; };",
3838 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3839}
3840
3841TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3842 EXPECT_TRUE(matches(
3843 "class A { class B { void f() { C c; } class C {}; }; };",
3844 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3845 hasAncestor(recordDecl(hasName("A"))))))));
3846}
3847
3848TEST(HasAncenstor, MatchesStatementAncestors) {
3849 EXPECT_TRUE(matches(
3850 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003851 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003852}
3853
3854TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3855 EXPECT_TRUE(matches(
3856 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003857 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003858}
3859
3860TEST(HasAncestor, BindsRecursiveCombinations) {
3861 EXPECT_TRUE(matchAndVerifyResultTrue(
3862 "class C { class D { class E { class F { int y; }; }; }; };",
3863 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003864 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003865}
3866
3867TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3868 EXPECT_TRUE(matchAndVerifyResultTrue(
3869 "class C { class D { class E { class F { int y; }; }; }; };",
3870 fieldDecl(hasAncestor(
3871 decl(
3872 hasDescendant(recordDecl(isDefinition(),
3873 hasAncestor(recordDecl())))
3874 ).bind("d")
3875 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003876 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003877}
3878
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003879TEST(HasAncestor, MatchesClosestAncestor) {
3880 EXPECT_TRUE(matchAndVerifyResultTrue(
3881 "template <typename T> struct C {"
3882 " void f(int) {"
3883 " struct I { void g(T) { int x; } } i; i.g(42);"
3884 " }"
3885 "};"
3886 "template struct C<int>;",
3887 varDecl(hasName("x"),
3888 hasAncestor(functionDecl(hasParameter(
3889 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3890 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3891}
3892
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003893TEST(HasAncestor, MatchesInTemplateInstantiations) {
3894 EXPECT_TRUE(matches(
3895 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3896 "A<int>::B::C a;",
3897 fieldDecl(hasType(asString("int")),
3898 hasAncestor(recordDecl(hasName("A"))))));
3899}
3900
3901TEST(HasAncestor, MatchesInImplicitCode) {
3902 EXPECT_TRUE(matches(
3903 "struct X {}; struct A { A() {} X x; };",
3904 constructorDecl(
3905 hasAnyConstructorInitializer(withInitializer(expr(
3906 hasAncestor(recordDecl(hasName("A")))))))));
3907}
3908
Daniel Jasper632aea92012-10-22 16:26:51 +00003909TEST(HasParent, MatchesOnlyParent) {
3910 EXPECT_TRUE(matches(
3911 "void f() { if (true) { int x = 42; } }",
3912 compoundStmt(hasParent(ifStmt()))));
3913 EXPECT_TRUE(notMatches(
3914 "void f() { for (;;) { int x = 42; } }",
3915 compoundStmt(hasParent(ifStmt()))));
3916 EXPECT_TRUE(notMatches(
3917 "void f() { if (true) for (;;) { int x = 42; } }",
3918 compoundStmt(hasParent(ifStmt()))));
3919}
3920
Manuel Klimekc844a462012-12-06 14:42:48 +00003921TEST(HasAncestor, MatchesAllAncestors) {
3922 EXPECT_TRUE(matches(
3923 "template <typename T> struct C { static void f() { 42; } };"
3924 "void t() { C<int>::f(); }",
3925 integerLiteral(
3926 equals(42),
3927 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3928 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3929}
3930
3931TEST(HasParent, MatchesAllParents) {
3932 EXPECT_TRUE(matches(
3933 "template <typename T> struct C { static void f() { 42; } };"
3934 "void t() { C<int>::f(); }",
3935 integerLiteral(
3936 equals(42),
3937 hasParent(compoundStmt(hasParent(functionDecl(
3938 hasParent(recordDecl(isTemplateInstantiation())))))))));
3939 EXPECT_TRUE(matches(
3940 "template <typename T> struct C { static void f() { 42; } };"
3941 "void t() { C<int>::f(); }",
3942 integerLiteral(
3943 equals(42),
3944 hasParent(compoundStmt(hasParent(functionDecl(
3945 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3946 EXPECT_TRUE(matches(
3947 "template <typename T> struct C { static void f() { 42; } };"
3948 "void t() { C<int>::f(); }",
3949 integerLiteral(equals(42),
3950 hasParent(compoundStmt(allOf(
3951 hasParent(functionDecl(
3952 hasParent(recordDecl(isTemplateInstantiation())))),
3953 hasParent(functionDecl(hasParent(recordDecl(
3954 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003955 EXPECT_TRUE(
3956 notMatches("template <typename T> struct C { static void f() {} };"
3957 "void t() { C<int>::f(); }",
3958 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003959}
3960
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003961TEST(HasParent, NoDuplicateParents) {
3962 class HasDuplicateParents : public BoundNodesCallback {
3963 public:
3964 bool run(const BoundNodes *Nodes) override { return false; }
3965 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3966 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3967 std::set<const void *> Parents;
3968 for (const auto &Parent : Context->getParents(*Node)) {
3969 if (!Parents.insert(Parent.getMemoizationData()).second) {
3970 return true;
3971 }
3972 }
3973 return false;
3974 }
3975 };
3976 EXPECT_FALSE(matchAndVerifyResultTrue(
3977 "template <typename T> int Foo() { return 1 + 2; }\n"
3978 "int x = Foo<int>() + Foo<unsigned>();",
3979 stmt().bind("node"), new HasDuplicateParents()));
3980}
3981
Daniel Jasper516b02e2012-10-17 08:52:59 +00003982TEST(TypeMatching, MatchesTypes) {
3983 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3984}
3985
Samuel Benzaquenb405c082014-12-15 15:09:22 +00003986TEST(TypeMatching, MatchesVoid) {
3987 EXPECT_TRUE(
3988 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
3989}
3990
Daniel Jasper516b02e2012-10-17 08:52:59 +00003991TEST(TypeMatching, MatchesArrayTypes) {
3992 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3993 EXPECT_TRUE(matches("int a[42];", arrayType()));
3994 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3995
3996 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3997 arrayType(hasElementType(builtinType()))));
3998
3999 EXPECT_TRUE(matches(
4000 "int const a[] = { 2, 3 };",
4001 qualType(arrayType(hasElementType(builtinType())))));
4002 EXPECT_TRUE(matches(
4003 "int const a[] = { 2, 3 };",
4004 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4005 EXPECT_TRUE(matches(
4006 "typedef const int T; T x[] = { 1, 2 };",
4007 qualType(isConstQualified(), arrayType())));
4008
4009 EXPECT_TRUE(notMatches(
4010 "int a[] = { 2, 3 };",
4011 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4012 EXPECT_TRUE(notMatches(
4013 "int a[] = { 2, 3 };",
4014 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
4015 EXPECT_TRUE(notMatches(
4016 "int const a[] = { 2, 3 };",
4017 qualType(arrayType(hasElementType(builtinType())),
4018 unless(isConstQualified()))));
4019
4020 EXPECT_TRUE(matches("int a[2];",
4021 constantArrayType(hasElementType(builtinType()))));
4022 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
4023}
4024
4025TEST(TypeMatching, MatchesComplexTypes) {
4026 EXPECT_TRUE(matches("_Complex float f;", complexType()));
4027 EXPECT_TRUE(matches(
4028 "_Complex float f;",
4029 complexType(hasElementType(builtinType()))));
4030 EXPECT_TRUE(notMatches(
4031 "_Complex float f;",
4032 complexType(hasElementType(isInteger()))));
4033}
4034
4035TEST(TypeMatching, MatchesConstantArrayTypes) {
4036 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
4037 EXPECT_TRUE(notMatches(
4038 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
4039 constantArrayType(hasElementType(builtinType()))));
4040
4041 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
4042 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
4043 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
4044}
4045
4046TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
4047 EXPECT_TRUE(matches(
4048 "template <typename T, int Size> class array { T data[Size]; };",
4049 dependentSizedArrayType()));
4050 EXPECT_TRUE(notMatches(
4051 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
4052 dependentSizedArrayType()));
4053}
4054
4055TEST(TypeMatching, MatchesIncompleteArrayType) {
4056 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
4057 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
4058
4059 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
4060 incompleteArrayType()));
4061}
4062
4063TEST(TypeMatching, MatchesVariableArrayType) {
4064 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
4065 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4066
4067 EXPECT_TRUE(matches(
4068 "void f(int b) { int a[b]; }",
4069 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4070 varDecl(hasName("b")))))))));
4071}
4072
4073TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00004074 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4075 llvm::Triple::Win32) {
4076 // FIXME: Make this work for MSVC.
4077 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004078
David Majnemer197e2102014-03-05 06:32:38 +00004079 EXPECT_TRUE(matches("_Atomic(int) i;",
4080 atomicType(hasValueType(isInteger()))));
4081 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4082 atomicType(hasValueType(isInteger()))));
4083 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004084}
4085
4086TEST(TypeMatching, MatchesAutoTypes) {
4087 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4088 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4089 autoType()));
4090
Richard Smith061f1e22013-04-30 21:23:01 +00004091 // FIXME: Matching against the type-as-written can't work here, because the
4092 // type as written was not deduced.
4093 //EXPECT_TRUE(matches("auto a = 1;",
4094 // autoType(hasDeducedType(isInteger()))));
4095 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4096 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004097}
4098
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004099TEST(TypeMatching, MatchesFunctionTypes) {
4100 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4101 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4102}
4103
Edwin Vaneec074802013-04-01 18:33:34 +00004104TEST(TypeMatching, MatchesParenType) {
4105 EXPECT_TRUE(
4106 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4107 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4108
4109 EXPECT_TRUE(matches(
4110 "int (*ptr_to_func)(int);",
4111 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4112 EXPECT_TRUE(notMatches(
4113 "int (*ptr_to_array)[4];",
4114 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4115}
4116
Daniel Jasper516b02e2012-10-17 08:52:59 +00004117TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004118 // FIXME: Reactive when these tests can be more specific (not matching
4119 // implicit code on certain platforms), likely when we have hasDescendant for
4120 // Types/TypeLocs.
4121 //EXPECT_TRUE(matchAndVerifyResultTrue(
4122 // "int* a;",
4123 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4124 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4125 //EXPECT_TRUE(matchAndVerifyResultTrue(
4126 // "int* a;",
4127 // pointerTypeLoc().bind("loc"),
4128 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004129 EXPECT_TRUE(matches(
4130 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004131 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004132 EXPECT_TRUE(matches(
4133 "int** a;",
4134 loc(pointerType(pointee(pointerType())))));
4135 EXPECT_TRUE(matches(
4136 "int* b; int* * const a = &b;",
4137 loc(qualType(isConstQualified(), pointerType()))));
4138
4139 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004140 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4141 hasType(blockPointerType()))));
4142 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4143 hasType(memberPointerType()))));
4144 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4145 hasType(pointerType()))));
4146 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4147 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004148 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4149 hasType(lValueReferenceType()))));
4150 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4151 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004152
Daniel Jasper7943eb52012-10-17 13:35:36 +00004153 Fragment = "int *ptr;";
4154 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4155 hasType(blockPointerType()))));
4156 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4157 hasType(memberPointerType()))));
4158 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4159 hasType(pointerType()))));
4160 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4161 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004162
Daniel Jasper7943eb52012-10-17 13:35:36 +00004163 Fragment = "int a; int &ref = a;";
4164 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4165 hasType(blockPointerType()))));
4166 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4167 hasType(memberPointerType()))));
4168 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4169 hasType(pointerType()))));
4170 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4171 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004172 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4173 hasType(lValueReferenceType()))));
4174 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4175 hasType(rValueReferenceType()))));
4176
4177 Fragment = "int &&ref = 2;";
4178 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4179 hasType(blockPointerType()))));
4180 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4181 hasType(memberPointerType()))));
4182 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4183 hasType(pointerType()))));
4184 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4185 hasType(referenceType()))));
4186 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4187 hasType(lValueReferenceType()))));
4188 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4189 hasType(rValueReferenceType()))));
4190}
4191
4192TEST(TypeMatching, AutoRefTypes) {
4193 std::string Fragment = "auto a = 1;"
4194 "auto b = a;"
4195 "auto &c = a;"
4196 "auto &&d = c;"
4197 "auto &&e = 2;";
4198 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4199 hasType(referenceType()))));
4200 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4201 hasType(referenceType()))));
4202 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4203 hasType(referenceType()))));
4204 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4205 hasType(lValueReferenceType()))));
4206 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4207 hasType(rValueReferenceType()))));
4208 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4209 hasType(referenceType()))));
4210 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4211 hasType(lValueReferenceType()))));
4212 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4213 hasType(rValueReferenceType()))));
4214 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4215 hasType(referenceType()))));
4216 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4217 hasType(lValueReferenceType()))));
4218 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4219 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004220}
4221
4222TEST(TypeMatching, PointeeTypes) {
4223 EXPECT_TRUE(matches("int b; int &a = b;",
4224 referenceType(pointee(builtinType()))));
4225 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4226
4227 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004228 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004229
4230 EXPECT_TRUE(matches(
4231 "int const *A;",
4232 pointerType(pointee(isConstQualified(), builtinType()))));
4233 EXPECT_TRUE(notMatches(
4234 "int *A;",
4235 pointerType(pointee(isConstQualified(), builtinType()))));
4236}
4237
4238TEST(TypeMatching, MatchesPointersToConstTypes) {
4239 EXPECT_TRUE(matches("int b; int * const a = &b;",
4240 loc(pointerType())));
4241 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004242 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004243 EXPECT_TRUE(matches(
4244 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004245 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004246 EXPECT_TRUE(matches(
4247 "int b; const int * a = &b;",
4248 pointerType(pointee(builtinType()))));
4249}
4250
4251TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004252 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4253 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004254}
4255
Edwin Vanef901b712013-02-25 14:49:29 +00004256TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004257 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004258 templateSpecializationType()));
4259}
4260
Edwin Vaneb6eae142013-02-25 20:43:32 +00004261TEST(TypeMatching, MatchesRecordType) {
4262 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004263 EXPECT_TRUE(matches("struct S{}; S s;",
4264 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4265 EXPECT_TRUE(notMatches("int i;",
4266 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004267}
4268
4269TEST(TypeMatching, MatchesElaboratedType) {
4270 EXPECT_TRUE(matches(
4271 "namespace N {"
4272 " namespace M {"
4273 " class D {};"
4274 " }"
4275 "}"
4276 "N::M::D d;", elaboratedType()));
4277 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4278 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4279}
4280
4281TEST(ElaboratedTypeNarrowing, hasQualifier) {
4282 EXPECT_TRUE(matches(
4283 "namespace N {"
4284 " namespace M {"
4285 " class D {};"
4286 " }"
4287 "}"
4288 "N::M::D d;",
4289 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4290 EXPECT_TRUE(notMatches(
4291 "namespace M {"
4292 " class D {};"
4293 "}"
4294 "M::D d;",
4295 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004296 EXPECT_TRUE(notMatches(
4297 "struct D {"
4298 "} d;",
4299 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004300}
4301
4302TEST(ElaboratedTypeNarrowing, namesType) {
4303 EXPECT_TRUE(matches(
4304 "namespace N {"
4305 " namespace M {"
4306 " class D {};"
4307 " }"
4308 "}"
4309 "N::M::D d;",
4310 elaboratedType(elaboratedType(namesType(recordType(
4311 hasDeclaration(namedDecl(hasName("D")))))))));
4312 EXPECT_TRUE(notMatches(
4313 "namespace M {"
4314 " class D {};"
4315 "}"
4316 "M::D d;",
4317 elaboratedType(elaboratedType(namesType(typedefType())))));
4318}
4319
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004320TEST(NNS, MatchesNestedNameSpecifiers) {
4321 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4322 nestedNameSpecifier()));
4323 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4324 nestedNameSpecifier()));
4325 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4326 nestedNameSpecifier()));
4327
4328 EXPECT_TRUE(matches(
4329 "struct A { static void f() {} }; void g() { A::f(); }",
4330 nestedNameSpecifier()));
4331 EXPECT_TRUE(notMatches(
4332 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4333 nestedNameSpecifier()));
4334}
4335
Daniel Jasper87c3d362012-09-20 14:12:57 +00004336TEST(NullStatement, SimpleCases) {
4337 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4338 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4339}
4340
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004341TEST(NNS, MatchesTypes) {
4342 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4343 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4344 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4345 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4346 Matcher));
4347 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4348}
4349
4350TEST(NNS, MatchesNamespaceDecls) {
4351 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4352 specifiesNamespace(hasName("ns")));
4353 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4354 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4355 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4356}
4357
4358TEST(NNS, BindsNestedNameSpecifiers) {
4359 EXPECT_TRUE(matchAndVerifyResultTrue(
4360 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4361 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4362 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4363}
4364
4365TEST(NNS, BindsNestedNameSpecifierLocs) {
4366 EXPECT_TRUE(matchAndVerifyResultTrue(
4367 "namespace ns { struct B {}; } ns::B b;",
4368 loc(nestedNameSpecifier()).bind("loc"),
4369 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4370}
4371
4372TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4373 EXPECT_TRUE(matches(
4374 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4375 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4376 EXPECT_TRUE(matches(
4377 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004378 nestedNameSpecifierLoc(hasPrefix(
4379 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004380}
4381
Daniel Jasper6fc34332012-10-30 15:42:00 +00004382TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4383 std::string Fragment =
4384 "namespace a { struct A { struct B { struct C {}; }; }; };"
4385 "void f() { a::A::B::C c; }";
4386 EXPECT_TRUE(matches(
4387 Fragment,
4388 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4389 hasDescendant(nestedNameSpecifier(
4390 specifiesNamespace(hasName("a")))))));
4391 EXPECT_TRUE(notMatches(
4392 Fragment,
4393 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4394 has(nestedNameSpecifier(
4395 specifiesNamespace(hasName("a")))))));
4396 EXPECT_TRUE(matches(
4397 Fragment,
4398 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4399 has(nestedNameSpecifier(
4400 specifiesNamespace(hasName("a")))))));
4401
4402 // Not really useful because a NestedNameSpecifier can af at most one child,
4403 // but to complete the interface.
4404 EXPECT_TRUE(matchAndVerifyResultTrue(
4405 Fragment,
4406 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4407 forEach(nestedNameSpecifier().bind("x"))),
4408 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4409}
4410
4411TEST(NNS, NestedNameSpecifiersAsDescendants) {
4412 std::string Fragment =
4413 "namespace a { struct A { struct B { struct C {}; }; }; };"
4414 "void f() { a::A::B::C c; }";
4415 EXPECT_TRUE(matches(
4416 Fragment,
4417 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4418 asString("struct a::A")))))));
4419 EXPECT_TRUE(matchAndVerifyResultTrue(
4420 Fragment,
4421 functionDecl(hasName("f"),
4422 forEachDescendant(nestedNameSpecifier().bind("x"))),
4423 // Nested names: a, a::A and a::A::B.
4424 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4425}
4426
4427TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4428 std::string Fragment =
4429 "namespace a { struct A { struct B { struct C {}; }; }; };"
4430 "void f() { a::A::B::C c; }";
4431 EXPECT_TRUE(matches(
4432 Fragment,
4433 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4434 hasDescendant(loc(nestedNameSpecifier(
4435 specifiesNamespace(hasName("a"))))))));
4436 EXPECT_TRUE(notMatches(
4437 Fragment,
4438 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4439 has(loc(nestedNameSpecifier(
4440 specifiesNamespace(hasName("a"))))))));
4441 EXPECT_TRUE(matches(
4442 Fragment,
4443 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4444 has(loc(nestedNameSpecifier(
4445 specifiesNamespace(hasName("a"))))))));
4446
4447 EXPECT_TRUE(matchAndVerifyResultTrue(
4448 Fragment,
4449 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4450 forEach(nestedNameSpecifierLoc().bind("x"))),
4451 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4452}
4453
4454TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4455 std::string Fragment =
4456 "namespace a { struct A { struct B { struct C {}; }; }; };"
4457 "void f() { a::A::B::C c; }";
4458 EXPECT_TRUE(matches(
4459 Fragment,
4460 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4461 asString("struct a::A"))))))));
4462 EXPECT_TRUE(matchAndVerifyResultTrue(
4463 Fragment,
4464 functionDecl(hasName("f"),
4465 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4466 // Nested names: a, a::A and a::A::B.
4467 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4468}
4469
Manuel Klimek191c0932013-02-01 13:41:35 +00004470template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004471public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004472 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4473 StringRef InnerId)
4474 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004475 }
4476
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004477 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004478
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004479 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004480 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004481 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4482 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004483 }
4484private:
4485 std::string Id;
4486 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004487 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004488};
4489
4490TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004491 EXPECT_TRUE(matchAndVerifyResultTrue(
4492 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4493 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004494 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4495 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004496 EXPECT_TRUE(matchAndVerifyResultFalse(
4497 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4498 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004499 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4500 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004501}
4502
4503TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004504 EXPECT_TRUE(matchAndVerifyResultTrue(
4505 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004506 new VerifyMatchOnNode<clang::Stmt>(
4507 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004508 EXPECT_TRUE(matchAndVerifyResultFalse(
4509 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004510 new VerifyMatchOnNode<clang::Stmt>(
4511 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004512}
4513
4514TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4515 EXPECT_TRUE(matchAndVerifyResultTrue(
4516 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4517 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004518 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004519 EXPECT_TRUE(matchAndVerifyResultFalse(
4520 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4521 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004522 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004523}
4524
Manuel Klimekbee08572013-02-07 12:42:10 +00004525template <typename T>
4526class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4527public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004528 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004529
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004530 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004531 const T *Node = Nodes->getNodeAs<T>("");
4532 return verify(*Nodes, *Context, Node);
4533 }
4534
4535 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004536 // Use the original typed pointer to verify we can pass pointers to subtypes
4537 // to equalsNode.
4538 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004539 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004540 "", match(stmt(hasParent(
4541 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004542 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004543 }
4544 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004545 // Use the original typed pointer to verify we can pass pointers to subtypes
4546 // to equalsNode.
4547 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004548 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004549 "", match(decl(hasParent(
4550 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004551 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004552 }
4553};
4554
4555TEST(IsEqualTo, MatchesNodesByIdentity) {
4556 EXPECT_TRUE(matchAndVerifyResultTrue(
4557 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004558 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4559 EXPECT_TRUE(matchAndVerifyResultTrue(
4560 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4561 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004562}
4563
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004564TEST(MatchFinder, CheckProfiling) {
4565 MatchFinder::MatchFinderOptions Options;
4566 llvm::StringMap<llvm::TimeRecord> Records;
4567 Options.CheckProfiling.emplace(Records);
4568 MatchFinder Finder(std::move(Options));
4569
4570 struct NamedCallback : public MatchFinder::MatchCallback {
4571 void run(const MatchFinder::MatchResult &Result) override {}
4572 StringRef getID() const override { return "MyID"; }
4573 } Callback;
4574 Finder.addMatcher(decl(), &Callback);
4575 std::unique_ptr<FrontendActionFactory> Factory(
4576 newFrontendActionFactory(&Finder));
4577 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4578
4579 EXPECT_EQ(1u, Records.size());
4580 EXPECT_EQ("MyID", Records.begin()->getKey());
4581}
4582
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004583class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4584public:
4585 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004586 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004587 EXPECT_TRUE(Called);
4588 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004589 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004590 bool Called;
4591};
4592
4593TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4594 MatchFinder Finder;
4595 VerifyStartOfTranslationUnit VerifyCallback;
4596 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004597 std::unique_ptr<FrontendActionFactory> Factory(
4598 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004599 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4600 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004601
4602 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004603 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004604 ASSERT_TRUE(AST.get());
4605 Finder.matchAST(AST->getASTContext());
4606 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004607}
4608
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004609class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4610public:
4611 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004612 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004613 EXPECT_FALSE(Called);
4614 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004615 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004616 bool Called;
4617};
4618
4619TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4620 MatchFinder Finder;
4621 VerifyEndOfTranslationUnit VerifyCallback;
4622 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004623 std::unique_ptr<FrontendActionFactory> Factory(
4624 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004625 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4626 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004627
4628 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004629 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004630 ASSERT_TRUE(AST.get());
4631 Finder.matchAST(AST->getASTContext());
4632 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004633}
4634
Manuel Klimekbbb75852013-06-20 14:06:32 +00004635TEST(EqualsBoundNodeMatcher, QualType) {
4636 EXPECT_TRUE(matches(
4637 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4638 hasInitializer(ignoringParenImpCasts(
4639 hasType(qualType(equalsBoundNode("type"))))))));
4640 EXPECT_TRUE(notMatches("int i = 1.f;",
4641 varDecl(hasType(qualType().bind("type")),
4642 hasInitializer(ignoringParenImpCasts(hasType(
4643 qualType(equalsBoundNode("type"))))))));
4644}
4645
4646TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4647 EXPECT_TRUE(notMatches(
4648 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4649 hasInitializer(ignoringParenImpCasts(
4650 hasType(qualType(equalsBoundNode("type"))))))));
4651}
4652
4653TEST(EqualsBoundNodeMatcher, Stmt) {
4654 EXPECT_TRUE(
4655 matches("void f() { if(true) {} }",
4656 stmt(allOf(ifStmt().bind("if"),
4657 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4658
4659 EXPECT_TRUE(notMatches(
4660 "void f() { if(true) { if (true) {} } }",
4661 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4662}
4663
4664TEST(EqualsBoundNodeMatcher, Decl) {
4665 EXPECT_TRUE(matches(
4666 "class X { class Y {}; };",
4667 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4668 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4669
4670 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4671 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4672 has(decl(equalsBoundNode("record")))))));
4673}
4674
4675TEST(EqualsBoundNodeMatcher, Type) {
4676 EXPECT_TRUE(matches(
4677 "class X { int a; int b; };",
4678 recordDecl(
4679 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4680 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4681
4682 EXPECT_TRUE(notMatches(
4683 "class X { int a; double b; };",
4684 recordDecl(
4685 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4686 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4687}
4688
4689TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004690 EXPECT_TRUE(matchAndVerifyResultTrue(
4691 "int f() {"
4692 " if (1) {"
4693 " int i = 9;"
4694 " }"
4695 " int j = 10;"
4696 " {"
4697 " float k = 9.0;"
4698 " }"
4699 " return 0;"
4700 "}",
4701 // Look for variable declarations within functions whose type is the same
4702 // as the function return type.
4703 functionDecl(returns(qualType().bind("type")),
4704 forEachDescendant(varDecl(hasType(
4705 qualType(equalsBoundNode("type")))).bind("decl"))),
4706 // Only i and j should match, not k.
4707 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4708}
4709
4710TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4711 EXPECT_TRUE(matchAndVerifyResultTrue(
4712 "void f() {"
4713 " int x;"
4714 " double d;"
4715 " x = d + x - d + x;"
4716 "}",
4717 functionDecl(
4718 hasName("f"), forEachDescendant(varDecl().bind("d")),
4719 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4720 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4721}
4722
Manuel Klimekce68f772014-03-25 14:39:26 +00004723TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4724 EXPECT_TRUE(matchAndVerifyResultTrue(
4725 "struct StringRef { int size() const; const char* data() const; };"
4726 "void f(StringRef v) {"
4727 " v.data();"
4728 "}",
4729 memberCallExpr(
4730 callee(methodDecl(hasName("data"))),
4731 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4732 .bind("var")))),
4733 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4734 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4735 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4736 .bind("data"),
4737 new VerifyIdIsBoundTo<Expr>("data", 1)));
4738
4739 EXPECT_FALSE(matches(
4740 "struct StringRef { int size() const; const char* data() const; };"
4741 "void f(StringRef v) {"
4742 " v.data();"
4743 " v.size();"
4744 "}",
4745 memberCallExpr(
4746 callee(methodDecl(hasName("data"))),
4747 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4748 .bind("var")))),
4749 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4750 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4751 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4752 .bind("data")));
4753}
4754
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004755TEST(TypeDefDeclMatcher, Match) {
4756 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4757 typedefDecl(hasName("typedefDeclTest"))));
4758}
4759
4760// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4761#ifndef LLVM_ON_WIN32
4762
4763TEST(Matcher, IsExpansionInMainFileMatcher) {
4764 EXPECT_TRUE(matches("class X {};",
4765 recordDecl(hasName("X"), isExpansionInMainFile())));
4766 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4767 FileContentMappings M;
4768 M.push_back(std::make_pair("/other", "class X {};"));
4769 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4770 recordDecl(isExpansionInMainFile()), false,
4771 "-isystem/", M));
4772}
4773
4774TEST(Matcher, IsExpansionInSystemHeader) {
4775 FileContentMappings M;
4776 M.push_back(std::make_pair("/other", "class X {};"));
4777 EXPECT_TRUE(matchesConditionally(
4778 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4779 "-isystem/", M));
4780 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4781 recordDecl(isExpansionInSystemHeader()),
4782 false, "-I/", M));
4783 EXPECT_TRUE(notMatches("class X {};",
4784 recordDecl(isExpansionInSystemHeader())));
4785 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4786}
4787
4788TEST(Matcher, IsExpansionInFileMatching) {
4789 FileContentMappings M;
4790 M.push_back(std::make_pair("/foo", "class A {};"));
4791 M.push_back(std::make_pair("/bar", "class B {};"));
4792 EXPECT_TRUE(matchesConditionally(
4793 "#include <foo>\n"
4794 "#include <bar>\n"
4795 "class X {};",
4796 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4797 "-isystem/", M));
4798 EXPECT_TRUE(matchesConditionally(
4799 "#include <foo>\n"
4800 "#include <bar>\n"
4801 "class X {};",
4802 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4803 "-isystem/", M));
4804}
4805
4806#endif // LLVM_ON_WIN32
4807
Manuel Klimekbfa43572015-03-12 15:48:15 +00004808
4809TEST(ObjCMessageExprMatcher, SimpleExprs) {
4810 // don't find ObjCMessageExpr where none are present
4811 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
4812
4813 std::string Objc1String =
4814 "@interface Str "
4815 " - (Str *)uppercaseString:(Str *)str;"
4816 "@end "
4817 "@interface foo "
4818 "- (void)meth:(Str *)text;"
4819 "@end "
4820 " "
4821 "@implementation foo "
4822 "- (void) meth:(Str *)text { "
4823 " [self contents];"
4824 " Str *up = [text uppercaseString];"
4825 "} "
4826 "@end ";
4827 EXPECT_TRUE(matchesObjC(
4828 Objc1String,
4829 objcMessageExpr(anything())));
4830 EXPECT_TRUE(matchesObjC(
4831 Objc1String,
4832 objcMessageExpr(hasSelector("contents"))));
4833 EXPECT_TRUE(matchesObjC(
4834 Objc1String,
4835 objcMessageExpr(matchesSelector("cont*"))));
4836 EXPECT_FALSE(matchesObjC(
4837 Objc1String,
4838 objcMessageExpr(matchesSelector("?cont*"))));
4839 EXPECT_TRUE(notMatchesObjC(
4840 Objc1String,
4841 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
4842 EXPECT_TRUE(matchesObjC(
4843 Objc1String,
4844 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
4845 EXPECT_TRUE(matchesObjC(
4846 Objc1String,
4847 objcMessageExpr(matchesSelector("uppercase*"),
4848 argumentCountIs(0)
4849 )));
4850
4851}
4852
Manuel Klimek04616e42012-07-06 05:48:52 +00004853} // end namespace ast_matchers
4854} // end namespace clang