blob: 4b0580a8147a9b97eb1be2e2c9c473dc3d02cae0 [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 Jasper9fcdc4612013-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 Jasper9fcdc4612013-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
Manuel Klimek04616e42012-07-06 05:48:52 +0000456TEST(DeclarationMatcher, MatchAnyOf) {
457 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000458 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000459 EXPECT_TRUE(
460 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
461 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
462 EXPECT_TRUE(
463 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
464 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
465
Daniel Jasper84c763e2012-07-15 19:57:12 +0000466 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000467 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000468 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
469 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
470
Manuel Klimek04616e42012-07-06 05:48:52 +0000471 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000472 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
473 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000474 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
475 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
476 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
477 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
478 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
479 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000480
481 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
482 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
483 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
484 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Manuel Klimek04616e42012-07-06 05:48:52 +0000485}
486
487TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000488 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000489 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
490 EXPECT_TRUE(matches("class X {};", HasClassX));
491
492 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000493 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000494 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
495 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
496 EXPECT_TRUE(
497 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
498}
499
500TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
501 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000502 recordDecl(
503 has(recordDecl(
504 has(recordDecl(hasName("X"))),
505 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000506 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000507 has(recordDecl(
508 has(recordDecl(hasName("A"))),
509 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000510 hasName("C"))),
511 hasName("F"));
512
513 EXPECT_TRUE(matches(
514 "class F {"
515 " class Z {"
516 " class X {};"
517 " class Y {};"
518 " };"
519 " class C {"
520 " class A {};"
521 " class B {};"
522 " };"
523 "};", Recursive));
524
525 EXPECT_TRUE(matches(
526 "class F {"
527 " class Z {"
528 " class A {};"
529 " class X {};"
530 " class Y {};"
531 " };"
532 " class C {"
533 " class X {};"
534 " class A {};"
535 " class B {};"
536 " };"
537 "};", Recursive));
538
539 EXPECT_TRUE(matches(
540 "class O1 {"
541 " class O2 {"
542 " class F {"
543 " class Z {"
544 " class A {};"
545 " class X {};"
546 " class Y {};"
547 " };"
548 " class C {"
549 " class X {};"
550 " class A {};"
551 " class B {};"
552 " };"
553 " };"
554 " };"
555 "};", Recursive));
556}
557
558TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
559 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000560 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000561 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000562 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000563 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000564 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000565 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000566 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000567 hasName("Y"))),
568 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000569 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000570 anyOf(
571 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000572 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000573 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000574 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000575 hasName("B")))))),
576 hasName("F")));
577
578 EXPECT_TRUE(matches("class F {};", Recursive));
579 EXPECT_TRUE(matches("class Z {};", Recursive));
580 EXPECT_TRUE(matches("class C {};", Recursive));
581 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
582 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
583 EXPECT_TRUE(
584 matches("class O1 { class O2 {"
585 " class M { class N { class B {}; }; }; "
586 "}; };", Recursive));
587}
588
589TEST(DeclarationMatcher, MatchNot) {
590 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000591 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000592 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000593 unless(hasName("X")));
594 EXPECT_TRUE(notMatches("", NotClassX));
595 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
596 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
597 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
598 EXPECT_TRUE(
599 notMatches("class Y {}; class Z {}; class X : public Y {};",
600 NotClassX));
601
602 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000603 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000604 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000605 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000606 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000607 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000608 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
609 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
610 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000611
612 DeclarationMatcher NamedNotRecord =
613 namedDecl(hasName("Foo"), unless(recordDecl()));
614 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
615 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000616}
617
618TEST(DeclarationMatcher, HasDescendant) {
619 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000620 recordDecl(
621 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000622 hasName("Z"));
623 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
624 EXPECT_TRUE(
625 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
626 EXPECT_TRUE(
627 matches("class Z { class A { class Y { class X {}; }; }; };",
628 ZDescendantClassX));
629 EXPECT_TRUE(
630 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
631 ZDescendantClassX));
632 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
633
634 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000635 recordDecl(
636 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000637 hasName("X"))),
638 hasName("Z"));
639 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
640 ZDescendantClassXHasClassY));
641 EXPECT_TRUE(
642 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
643 ZDescendantClassXHasClassY));
644 EXPECT_TRUE(notMatches(
645 "class Z {"
646 " class A {"
647 " class B {"
648 " class X {"
649 " class C {"
650 " class Y {};"
651 " };"
652 " };"
653 " }; "
654 " };"
655 "};", ZDescendantClassXHasClassY));
656
657 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000658 recordDecl(
659 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
660 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000661 hasName("Z"));
662 EXPECT_TRUE(
663 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
664 ZDescendantClassXDescendantClassY));
665 EXPECT_TRUE(matches(
666 "class Z {"
667 " class A {"
668 " class X {"
669 " class B {"
670 " class Y {};"
671 " };"
672 " class Y {};"
673 " };"
674 " };"
675 "};", ZDescendantClassXDescendantClassY));
676}
677
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000678TEST(DeclarationMatcher, HasDescendantMemoization) {
679 DeclarationMatcher CannotMemoize =
680 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
681 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
682}
683
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000684TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
685 auto Name = hasName("i");
686 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
687 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
688 // Matching VD first should not make a cache hit for RD.
689 EXPECT_TRUE(notMatches("void f() { int i; }",
690 decl(hasDescendant(VD), hasDescendant(RD))));
691 EXPECT_TRUE(notMatches("void f() { int i; }",
692 decl(hasDescendant(RD), hasDescendant(VD))));
693 // Not matching RD first should not make a cache hit for VD either.
694 EXPECT_TRUE(matches("void f() { int i; }",
695 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
696}
697
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000698TEST(DeclarationMatcher, HasAttr) {
699 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
700 decl(hasAttr(clang::attr::WarnUnused))));
701 EXPECT_FALSE(matches("struct X {};",
702 decl(hasAttr(clang::attr::WarnUnused))));
703}
704
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000705TEST(DeclarationMatcher, MatchCudaDecl) {
706 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
707 "void g() { f<<<1, 2>>>(); }",
708 CUDAKernelCallExpr()));
709 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000710 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000711 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000712 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000713 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000714 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000715}
716
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000717// Implements a run method that returns whether BoundNodes contains a
718// Decl bound to Id that can be dynamically cast to T.
719// Optionally checks that the check succeeded a specific number of times.
720template <typename T>
721class VerifyIdIsBoundTo : public BoundNodesCallback {
722public:
723 // Create an object that checks that a node of type \c T was bound to \c Id.
724 // Does not check for a certain number of matches.
725 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
726 : Id(Id), ExpectedCount(-1), Count(0) {}
727
728 // Create an object that checks that a node of type \c T was bound to \c Id.
729 // Checks that there were exactly \c ExpectedCount matches.
730 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
731 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
732
733 // Create an object that checks that a node of type \c T was bound to \c Id.
734 // Checks that there was exactly one match with the name \c ExpectedName.
735 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000736 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
737 int ExpectedCount = 1)
738 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
739 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000740
Craig Toppera798a9d2014-03-02 09:32:10 +0000741 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000742 if (ExpectedCount != -1)
743 EXPECT_EQ(ExpectedCount, Count);
744 if (!ExpectedName.empty())
745 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000746 Count = 0;
747 Name.clear();
748 }
749
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000750 ~VerifyIdIsBoundTo() override {
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000751 EXPECT_EQ(0, Count);
752 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000753 }
754
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000755 bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000756 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000757 if (Nodes->getNodeAs<T>(Id)) {
758 ++Count;
759 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
760 Name = Named->getNameAsString();
761 } else if (const NestedNameSpecifier *NNS =
762 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
763 llvm::raw_string_ostream OS(Name);
764 NNS->print(OS, PrintingPolicy(LangOptions()));
765 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000766 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
767 EXPECT_NE(M.end(), I);
768 if (I != M.end())
769 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000770 return true;
771 }
Craig Topper416fa342014-06-08 08:38:12 +0000772 EXPECT_TRUE(M.count(Id) == 0 ||
773 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000774 return false;
775 }
776
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000777 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000778 return run(Nodes);
779 }
780
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000781private:
782 const std::string Id;
783 const int ExpectedCount;
784 int Count;
785 const std::string ExpectedName;
786 std::string Name;
787};
788
789TEST(HasDescendant, MatchesDescendantTypes) {
790 EXPECT_TRUE(matches("void f() { int i = 3; }",
791 decl(hasDescendant(loc(builtinType())))));
792 EXPECT_TRUE(matches("void f() { int i = 3; }",
793 stmt(hasDescendant(builtinType()))));
794
795 EXPECT_TRUE(matches("void f() { int i = 3; }",
796 stmt(hasDescendant(loc(builtinType())))));
797 EXPECT_TRUE(matches("void f() { int i = 3; }",
798 stmt(hasDescendant(qualType(builtinType())))));
799
800 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
801 stmt(hasDescendant(isInteger()))));
802
803 EXPECT_TRUE(matchAndVerifyResultTrue(
804 "void f() { int a; float c; int d; int e; }",
805 functionDecl(forEachDescendant(
806 varDecl(hasDescendant(isInteger())).bind("x"))),
807 new VerifyIdIsBoundTo<Decl>("x", 3)));
808}
809
810TEST(HasDescendant, MatchesDescendantsOfTypes) {
811 EXPECT_TRUE(matches("void f() { int*** i; }",
812 qualType(hasDescendant(builtinType()))));
813 EXPECT_TRUE(matches("void f() { int*** i; }",
814 qualType(hasDescendant(
815 pointerType(pointee(builtinType()))))));
816 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000817 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000818
819 EXPECT_TRUE(matchAndVerifyResultTrue(
820 "void f() { int*** i; }",
821 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
822 new VerifyIdIsBoundTo<Type>("x", 2)));
823}
824
825TEST(Has, MatchesChildrenOfTypes) {
826 EXPECT_TRUE(matches("int i;",
827 varDecl(hasName("i"), has(isInteger()))));
828 EXPECT_TRUE(notMatches("int** i;",
829 varDecl(hasName("i"), has(isInteger()))));
830 EXPECT_TRUE(matchAndVerifyResultTrue(
831 "int (*f)(float, int);",
832 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
833 new VerifyIdIsBoundTo<QualType>("x", 2)));
834}
835
836TEST(Has, MatchesChildTypes) {
837 EXPECT_TRUE(matches(
838 "int* i;",
839 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
840 EXPECT_TRUE(notMatches(
841 "int* i;",
842 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
843}
844
Samuel Benzaquenc640ef52014-10-28 13:33:58 +0000845TEST(ValueDecl, Matches) {
846 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
847 valueDecl(hasType(asString("enum EnumType")))));
848 EXPECT_TRUE(matches("void FunctionDecl();",
849 valueDecl(hasType(asString("void (void)")))));
850}
851
Daniel Jasper1dad1832012-07-10 20:20:19 +0000852TEST(Enum, DoesNotMatchClasses) {
853 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
854}
855
856TEST(Enum, MatchesEnums) {
857 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
858}
859
860TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000861 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000862 EXPECT_TRUE(matches("enum X{ A };", Matcher));
863 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
864 EXPECT_TRUE(notMatches("enum X {};", Matcher));
865}
866
Manuel Klimek04616e42012-07-06 05:48:52 +0000867TEST(StatementMatcher, Has) {
868 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000869 expr(hasType(pointsTo(recordDecl(hasName("X")))),
870 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000871
872 EXPECT_TRUE(matches(
873 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
874 EXPECT_TRUE(notMatches(
875 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
876}
877
878TEST(StatementMatcher, HasDescendant) {
879 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000880 expr(hasType(pointsTo(recordDecl(hasName("X")))),
881 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000882
883 EXPECT_TRUE(matches(
884 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
885 HasDescendantVariableI));
886 EXPECT_TRUE(notMatches(
887 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
888 HasDescendantVariableI));
889}
890
891TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000892 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000893
894 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
895 EXPECT_TRUE(notMatches("class A {};", TypeA));
896
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000897 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000898
899 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
900 TypeDerivedFromA));
901 EXPECT_TRUE(notMatches("class A {};", TypeA));
902
903 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000904 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000905
906 EXPECT_TRUE(
907 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
908}
909
Manuel Klimek04616e42012-07-06 05:48:52 +0000910TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000911 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000912
913 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000914 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000915
916 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000917 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000918
919 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000920 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000921
922 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
923 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000924 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000925
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000926 StatementMatcher MethodX =
927 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000928
929 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
930 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000931 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000932}
933
934TEST(Matcher, BindTheSameNameInAlternatives) {
935 StatementMatcher matcher = anyOf(
936 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000937 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000938 hasRHS(integerLiteral(equals(0)))),
939 binaryOperator(hasOperatorName("+"),
940 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000941 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000942
943 EXPECT_TRUE(matchAndVerifyResultTrue(
944 // The first branch of the matcher binds x to 0 but then fails.
945 // The second branch binds x to f() and succeeds.
946 "int f() { return 0 + f(); }",
947 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000948 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000949}
950
Manuel Klimekfdf98762012-08-30 19:41:06 +0000951TEST(Matcher, BindsIDForMemoizedResults) {
952 // Using the same matcher in two match expressions will make memoization
953 // kick in.
954 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
955 EXPECT_TRUE(matchAndVerifyResultTrue(
956 "class A { class B { class X {}; }; };",
957 DeclarationMatcher(anyOf(
958 recordDecl(hasName("A"), hasDescendant(ClassX)),
959 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000960 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000961}
962
Daniel Jasper856194d02012-12-03 15:43:25 +0000963TEST(HasDeclaration, HasDeclarationOfEnumType) {
964 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
965 expr(hasType(pointsTo(
966 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
967}
968
Edwin Vaneed936452013-02-25 14:32:42 +0000969TEST(HasDeclaration, HasGetDeclTraitTest) {
970 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
971 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
972 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
973}
974
Edwin Vane2c197e02013-02-19 17:14:34 +0000975TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
976 EXPECT_TRUE(matches("typedef int X; X a;",
977 varDecl(hasName("a"),
978 hasType(typedefType(hasDeclaration(decl()))))));
979
980 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
981}
982
Edwin Vanef901b712013-02-25 14:49:29 +0000983TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
984 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
985 varDecl(hasType(templateSpecializationType(
986 hasDeclaration(namedDecl(hasName("A"))))))));
987}
988
Manuel Klimek04616e42012-07-06 05:48:52 +0000989TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000990 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000991 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000992 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000993 EXPECT_TRUE(
994 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000995 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000996 EXPECT_TRUE(
997 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000998 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000999}
1000
1001TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001002 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001003 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001004 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001005 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001006 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001007 EXPECT_TRUE(
1008 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001009 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001010}
1011
1012TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001013 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001014 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001015 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001016 EXPECT_TRUE(
1017 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001018 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001019}
1020
1021TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001022 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001023 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001024 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001025 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001026 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001027}
1028
Manuel Klimekc16c6522013-06-20 13:08:29 +00001029TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1030 EXPECT_TRUE(matches("int x;",
1031 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1032
1033 // Make sure we don't crash on implicit constructors.
1034 EXPECT_TRUE(notMatches("class X {}; X x;",
1035 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1036}
1037
Manuel Klimek04616e42012-07-06 05:48:52 +00001038TEST(Matcher, Call) {
1039 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001040 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001041 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001042
1043 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1044 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1045
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001046 StatementMatcher MethodOnY =
1047 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001048
1049 EXPECT_TRUE(
1050 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1051 MethodOnY));
1052 EXPECT_TRUE(
1053 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1054 MethodOnY));
1055 EXPECT_TRUE(
1056 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1057 MethodOnY));
1058 EXPECT_TRUE(
1059 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1060 MethodOnY));
1061 EXPECT_TRUE(
1062 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1063 MethodOnY));
1064
1065 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001066 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001067
1068 EXPECT_TRUE(
1069 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1070 MethodOnYPointer));
1071 EXPECT_TRUE(
1072 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1073 MethodOnYPointer));
1074 EXPECT_TRUE(
1075 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1076 MethodOnYPointer));
1077 EXPECT_TRUE(
1078 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1079 MethodOnYPointer));
1080 EXPECT_TRUE(
1081 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1082 MethodOnYPointer));
1083}
1084
Daniel Jasper5901e472012-10-01 13:40:41 +00001085TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001086 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001087 lambdaExpr()));
1088}
1089
1090TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001091 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1092 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001093 forRangeStmt()));
1094 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1095 forRangeStmt()));
1096}
1097
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001098TEST(Matcher, SubstNonTypeTemplateParm) {
1099 EXPECT_FALSE(matches("template<int N>\n"
1100 "struct A { static const int n = 0; };\n"
1101 "struct B : public A<42> {};",
1102 substNonTypeTemplateParmExpr()));
1103 EXPECT_TRUE(matches("template<int N>\n"
1104 "struct A { static const int n = N; };\n"
1105 "struct B : public A<42> {};",
1106 substNonTypeTemplateParmExpr()));
1107}
1108
Daniel Jasper5901e472012-10-01 13:40:41 +00001109TEST(Matcher, UserDefinedLiteral) {
1110 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1111 " return i + 1;"
1112 "}"
1113 "char c = 'a'_inc;",
1114 userDefinedLiteral()));
1115}
1116
Daniel Jasper87c3d362012-09-20 14:12:57 +00001117TEST(Matcher, FlowControl) {
1118 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1119 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1120 continueStmt()));
1121 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1122 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1123 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1124}
1125
Daniel Jasper1dad1832012-07-10 20:20:19 +00001126TEST(HasType, MatchesAsString) {
1127 EXPECT_TRUE(
1128 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001129 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001130 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001131 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001132 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001133 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001134 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001135 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001136}
1137
Manuel Klimek04616e42012-07-06 05:48:52 +00001138TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001139 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001140 // Unary operator
1141 EXPECT_TRUE(matches("class Y { }; "
1142 "bool operator!(Y x) { return false; }; "
1143 "Y y; bool c = !y;", OpCall));
1144 // No match -- special operators like "new", "delete"
1145 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1146 // we need to figure out include paths in the test.
1147 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1148 // "class Y { }; "
1149 // "void *operator new(size_t size) { return 0; } "
1150 // "Y *y = new Y;", OpCall));
1151 EXPECT_TRUE(notMatches("class Y { }; "
1152 "void operator delete(void *p) { } "
1153 "void a() {Y *y = new Y; delete y;}", OpCall));
1154 // Binary operator
1155 EXPECT_TRUE(matches("class Y { }; "
1156 "bool operator&&(Y x, Y y) { return true; }; "
1157 "Y a; Y b; bool c = a && b;",
1158 OpCall));
1159 // No match -- normal operator, not an overloaded one.
1160 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1161 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1162}
1163
1164TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1165 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001166 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001167 EXPECT_TRUE(matches("class Y { }; "
1168 "bool operator&&(Y x, Y y) { return true; }; "
1169 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1170 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001171 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001172 EXPECT_TRUE(notMatches("class Y { }; "
1173 "bool operator&&(Y x, Y y) { return true; }; "
1174 "Y a; Y b; bool c = a && b;",
1175 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001176 StatementMatcher OpStarCall =
1177 operatorCallExpr(hasOverloadedOperatorName("*"));
1178 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1179 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001180 DeclarationMatcher ClassWithOpStar =
1181 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1182 EXPECT_TRUE(matches("class Y { int operator*(); };",
1183 ClassWithOpStar));
1184 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1185 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001186 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1187 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1188 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001189}
1190
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001191TEST(Matcher, NestedOverloadedOperatorCalls) {
1192 EXPECT_TRUE(matchAndVerifyResultTrue(
1193 "class Y { }; "
1194 "Y& operator&&(Y& x, Y& y) { return x; }; "
1195 "Y a; Y b; Y c; Y d = a && b && c;",
1196 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1197 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1198 EXPECT_TRUE(matches(
1199 "class Y { }; "
1200 "Y& operator&&(Y& x, Y& y) { return x; }; "
1201 "Y a; Y b; Y c; Y d = a && b && c;",
1202 operatorCallExpr(hasParent(operatorCallExpr()))));
1203 EXPECT_TRUE(matches(
1204 "class Y { }; "
1205 "Y& operator&&(Y& x, Y& y) { return x; }; "
1206 "Y a; Y b; Y c; Y d = a && b && c;",
1207 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1208}
1209
Manuel Klimek04616e42012-07-06 05:48:52 +00001210TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001211 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001212 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001213
1214 EXPECT_TRUE(
1215 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1216 MethodOnY));
1217 EXPECT_TRUE(
1218 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1219 MethodOnY));
1220 EXPECT_TRUE(
1221 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1222 MethodOnY));
1223 EXPECT_TRUE(
1224 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1225 MethodOnY));
1226 EXPECT_TRUE(
1227 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1228 MethodOnY));
1229
1230 EXPECT_TRUE(matches(
1231 "class Y {"
1232 " public: virtual void x();"
1233 "};"
1234 "class X : public Y {"
1235 " public: virtual void x();"
1236 "};"
1237 "void z() { X *x; x->Y::x(); }", MethodOnY));
1238}
1239
1240TEST(Matcher, VariableUsage) {
1241 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001242 declRefExpr(to(
1243 varDecl(hasInitializer(
1244 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001245
1246 EXPECT_TRUE(matches(
1247 "class Y {"
1248 " public:"
1249 " bool x() const;"
1250 "};"
1251 "void z(const Y &y) {"
1252 " bool b = y.x();"
1253 " if (b) {}"
1254 "}", Reference));
1255
1256 EXPECT_TRUE(notMatches(
1257 "class Y {"
1258 " public:"
1259 " bool x() const;"
1260 "};"
1261 "void z(const Y &y) {"
1262 " bool b = y.x();"
1263 "}", Reference));
1264}
1265
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001266TEST(Matcher, VarDecl_Storage) {
1267 auto M = varDecl(hasName("X"), hasLocalStorage());
1268 EXPECT_TRUE(matches("void f() { int X; }", M));
1269 EXPECT_TRUE(notMatches("int X;", M));
1270 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1271
1272 M = varDecl(hasName("X"), hasGlobalStorage());
1273 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1274 EXPECT_TRUE(matches("int X;", M));
1275 EXPECT_TRUE(matches("void f() { static int X; }", M));
1276}
1277
Manuel Klimek61379422012-12-04 14:42:08 +00001278TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001279 EXPECT_TRUE(matches(
1280 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001281 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001282}
1283
Manuel Klimek04616e42012-07-06 05:48:52 +00001284TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001285 StatementMatcher CallOnVariableY =
1286 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001287
1288 EXPECT_TRUE(matches(
1289 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1290 EXPECT_TRUE(matches(
1291 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1292 EXPECT_TRUE(matches(
1293 "class Y { public: void x(); };"
1294 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1295 EXPECT_TRUE(matches(
1296 "class Y { public: void x(); };"
1297 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1298 EXPECT_TRUE(notMatches(
1299 "class Y { public: void x(); };"
1300 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1301 CallOnVariableY));
1302}
1303
Daniel Jasper1dad1832012-07-10 20:20:19 +00001304TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1305 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1306 unaryExprOrTypeTraitExpr()));
1307 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1308 alignOfExpr(anything())));
1309 // FIXME: Uncomment once alignof is enabled.
1310 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1311 // unaryExprOrTypeTraitExpr()));
1312 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1313 // sizeOfExpr()));
1314}
1315
1316TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1317 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1318 hasArgumentOfType(asString("int")))));
1319 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1320 hasArgumentOfType(asString("float")))));
1321 EXPECT_TRUE(matches(
1322 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001323 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001324 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001325 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001326}
1327
Manuel Klimek04616e42012-07-06 05:48:52 +00001328TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001329 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001330}
1331
1332TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001333 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001334}
1335
1336TEST(MemberExpression, MatchesVariable) {
1337 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001338 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001339 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001340 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001341 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001342 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001343}
1344
1345TEST(MemberExpression, MatchesStaticVariable) {
1346 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001347 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001348 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001349 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001350 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001351 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001352}
1353
Daniel Jasper4e566c42012-07-12 08:50:38 +00001354TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001355 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1356 EXPECT_TRUE(matches(
1357 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1358 callExpr(hasArgument(0, declRefExpr(
1359 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001360}
1361
1362TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001363 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001364 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001365 callExpr(hasArgument(0, declRefExpr(
1366 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001367}
1368
Manuel Klimek04616e42012-07-06 05:48:52 +00001369TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1370 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001371 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001372 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001373 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001374 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001375 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001376}
1377
1378TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1379 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001380 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001381 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001382 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001383 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001384 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001385}
1386
1387TEST(IsArrow, MatchesMemberCallsViaArrow) {
1388 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001389 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001390 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001391 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001392 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001393 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001394}
1395
1396TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001397 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001398
1399 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1400 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1401}
1402
1403TEST(Callee, MatchesMemberExpressions) {
1404 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001405 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001406 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001407 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001408}
1409
1410TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001411 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001412
1413 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1414 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1415
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001416 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1417 llvm::Triple::Win32) {
1418 // FIXME: Make this work for MSVC.
1419 // Dependent contexts, but a non-dependent call.
1420 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1421 CallFunctionF));
1422 EXPECT_TRUE(
1423 matches("void f(); template <int N> struct S { void g() { f(); } };",
1424 CallFunctionF));
1425 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001426
1427 // Depedent calls don't match.
1428 EXPECT_TRUE(
1429 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1430 CallFunctionF));
1431 EXPECT_TRUE(
1432 notMatches("void f(int);"
1433 "template <typename T> struct S { void g(T t) { f(t); } };",
1434 CallFunctionF));
1435}
1436
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001437TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1438 EXPECT_TRUE(
1439 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001440 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001441}
1442
1443TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1444 EXPECT_TRUE(
1445 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001446 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001447}
1448
1449TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1450 EXPECT_TRUE(
1451 notMatches("void g(); template <typename T> void f(T t) {}"
1452 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001453 functionTemplateDecl(hasName("f"),
1454 hasDescendant(declRefExpr(to(
1455 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001456}
1457
Manuel Klimek04616e42012-07-06 05:48:52 +00001458TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001459 StatementMatcher CallArgumentY = callExpr(
1460 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001461
1462 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1463 EXPECT_TRUE(
1464 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1465 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1466
Daniel Jasper848cbe12012-09-18 13:09:13 +00001467 StatementMatcher WrongIndex = callExpr(
1468 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001469 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1470}
1471
1472TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001473 StatementMatcher CallArgumentY = callExpr(
1474 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001475 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1476 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1477 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1478}
1479
1480TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001481 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001482
1483 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1484 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1485 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1486}
1487
Daniel Jasper9f501292012-12-04 11:54:27 +00001488TEST(Matcher, ParameterCount) {
1489 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1490 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1491 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1492 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1493 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1494}
1495
Manuel Klimek04616e42012-07-06 05:48:52 +00001496TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001497 DeclarationMatcher ReferenceClassX = varDecl(
1498 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001499 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1500 ReferenceClassX));
1501 EXPECT_TRUE(
1502 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001503 // The match here is on the implicit copy constructor code for
1504 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001505 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001506 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1507 EXPECT_TRUE(
1508 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001509 EXPECT_TRUE(
1510 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1511}
1512
Edwin Vane0a4836e2013-03-06 17:02:57 +00001513TEST(QualType, hasCanonicalType) {
1514 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1515 "int a;"
1516 "int_ref b = a;",
1517 varDecl(hasType(qualType(referenceType())))));
1518 EXPECT_TRUE(
1519 matches("typedef int &int_ref;"
1520 "int a;"
1521 "int_ref b = a;",
1522 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1523}
1524
Edwin Vane119d3df2013-04-02 18:15:55 +00001525TEST(QualType, hasLocalQualifiers) {
1526 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1527 varDecl(hasType(hasLocalQualifiers()))));
1528 EXPECT_TRUE(matches("int *const j = nullptr;",
1529 varDecl(hasType(hasLocalQualifiers()))));
1530 EXPECT_TRUE(matches("int *volatile k;",
1531 varDecl(hasType(hasLocalQualifiers()))));
1532 EXPECT_TRUE(notMatches("int m;",
1533 varDecl(hasType(hasLocalQualifiers()))));
1534}
1535
Manuel Klimek04616e42012-07-06 05:48:52 +00001536TEST(HasParameter, CallsInnerMatcher) {
1537 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001538 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001539 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001540 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001541}
1542
1543TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1544 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001545 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001546}
1547
1548TEST(HasType, MatchesParameterVariableTypesStrictly) {
1549 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001550 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001551 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001552 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001553 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001554 methodDecl(hasParameter(0,
1555 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001556 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001557 methodDecl(hasParameter(0,
1558 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001559}
1560
1561TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1562 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001563 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001564 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001565 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001566}
1567
Daniel Jasper1dad1832012-07-10 20:20:19 +00001568TEST(Returns, MatchesReturnTypes) {
1569 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001570 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001571 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001572 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001573 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001574 functionDecl(returns(hasDeclaration(
1575 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001576}
1577
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001578TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001579 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1580 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1581 functionDecl(isExternC())));
1582 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001583}
1584
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001585TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1586 EXPECT_TRUE(
1587 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1588 EXPECT_TRUE(matches("void Func() = delete;",
1589 functionDecl(hasName("Func"), isDeleted())));
1590}
1591
Manuel Klimek04616e42012-07-06 05:48:52 +00001592TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1593 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001594 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001595}
1596
1597TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1598 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001599 methodDecl(hasAnyParameter(hasType(pointsTo(
1600 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001601}
1602
Alp Toker8db6e7a2014-01-05 06:38:57 +00001603TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001604 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001605 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001606 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001607 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001608}
1609
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001610TEST(Matcher, MatchesClassTemplateSpecialization) {
1611 EXPECT_TRUE(matches("template<typename T> struct A {};"
1612 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001613 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001614 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001615 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001616 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001617 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001618}
1619
Manuel Klimekc16c6522013-06-20 13:08:29 +00001620TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1621 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1622 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1623}
1624
1625TEST(ParmVarDecl, MatchesParmVars) {
1626 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1627 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1628}
1629
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001630TEST(Matcher, MatchesTypeTemplateArgument) {
1631 EXPECT_TRUE(matches(
1632 "template<typename T> struct B {};"
1633 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001634 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001635 asString("int"))))));
1636}
1637
1638TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1639 EXPECT_TRUE(matches(
1640 "struct B { int next; };"
1641 "template<int(B::*next_ptr)> struct A {};"
1642 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001643 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1644 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001645
1646 EXPECT_TRUE(notMatches(
1647 "template <typename T> struct A {};"
1648 "A<int> a;",
1649 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1650 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001651
1652 EXPECT_TRUE(matches(
1653 "struct B { int next; };"
1654 "template<int(B::*next_ptr)> struct A {};"
1655 "A<&B::next> a;",
1656 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1657 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1658
1659 EXPECT_TRUE(notMatches(
1660 "template <typename T> struct A {};"
1661 "A<int> a;",
1662 templateSpecializationType(hasAnyTemplateArgument(
1663 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001664}
1665
1666TEST(Matcher, MatchesSpecificArgument) {
1667 EXPECT_TRUE(matches(
1668 "template<typename T, typename U> class A {};"
1669 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001670 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001671 1, refersToType(asString("int"))))));
1672 EXPECT_TRUE(notMatches(
1673 "template<typename T, typename U> class A {};"
1674 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001675 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001676 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001677
1678 EXPECT_TRUE(matches(
1679 "template<typename T, typename U> class A {};"
1680 "A<bool, int> a;",
1681 templateSpecializationType(hasTemplateArgument(
1682 1, refersToType(asString("int"))))));
1683 EXPECT_TRUE(notMatches(
1684 "template<typename T, typename U> class A {};"
1685 "A<int, bool> a;",
1686 templateSpecializationType(hasTemplateArgument(
1687 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001688}
1689
Manuel Klimek7735e402014-10-09 13:06:22 +00001690TEST(TemplateArgument, Matches) {
1691 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1692 classTemplateSpecializationDecl(
1693 hasAnyTemplateArgument(templateArgument()))));
1694 EXPECT_TRUE(matches(
1695 "template<typename T> struct C {}; C<int> c;",
1696 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1697}
1698
1699TEST(TemplateArgumentCountIs, Matches) {
1700 EXPECT_TRUE(
1701 matches("template<typename T> struct C {}; C<int> c;",
1702 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1703 EXPECT_TRUE(
1704 notMatches("template<typename T> struct C {}; C<int> c;",
1705 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1706
1707 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1708 templateSpecializationType(templateArgumentCountIs(1))));
1709 EXPECT_TRUE(
1710 notMatches("template<typename T> struct C {}; C<int> c;",
1711 templateSpecializationType(templateArgumentCountIs(2))));
1712}
1713
1714TEST(IsIntegral, Matches) {
1715 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1716 classTemplateSpecializationDecl(
1717 hasAnyTemplateArgument(isIntegral()))));
1718 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1719 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1720 templateArgument(isIntegral())))));
1721}
1722
1723TEST(RefersToIntegralType, Matches) {
1724 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1725 classTemplateSpecializationDecl(
1726 hasAnyTemplateArgument(refersToIntegralType(
1727 asString("int"))))));
1728 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1729 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1730 refersToIntegralType(asString("int"))))));
1731}
1732
1733TEST(EqualsIntegralValue, Matches) {
1734 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1735 classTemplateSpecializationDecl(
1736 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1737 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1738 classTemplateSpecializationDecl(
1739 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1740 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1741 classTemplateSpecializationDecl(
1742 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1743 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1744 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1745 equalsIntegralValue("0042")))));
1746}
1747
Daniel Jasper639522c2013-02-25 12:02:08 +00001748TEST(Matcher, MatchesAccessSpecDecls) {
1749 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1750 EXPECT_TRUE(
1751 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1752 EXPECT_TRUE(
1753 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1754 EXPECT_TRUE(
1755 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1756
1757 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1758}
1759
Edwin Vane37ee1d72013-04-09 20:46:36 +00001760TEST(Matcher, MatchesVirtualMethod) {
1761 EXPECT_TRUE(matches("class X { virtual int f(); };",
1762 methodDecl(isVirtual(), hasName("::X::f"))));
1763 EXPECT_TRUE(notMatches("class X { int f(); };",
1764 methodDecl(isVirtual())));
1765}
1766
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001767TEST(Matcher, MatchesPureMethod) {
1768 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1769 methodDecl(isPure(), hasName("::X::f"))));
1770 EXPECT_TRUE(notMatches("class X { int f(); };",
1771 methodDecl(isPure())));
1772}
1773
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001774TEST(Matcher, MatchesConstMethod) {
1775 EXPECT_TRUE(matches("struct A { void foo() const; };",
1776 methodDecl(isConst())));
1777 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1778 methodDecl(isConst())));
1779}
1780
Edwin Vane37ee1d72013-04-09 20:46:36 +00001781TEST(Matcher, MatchesOverridingMethod) {
1782 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1783 "class Y : public X { int f(); };",
1784 methodDecl(isOverride(), hasName("::Y::f"))));
1785 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1786 "class Y : public X { int f(); };",
1787 methodDecl(isOverride(), hasName("::X::f"))));
1788 EXPECT_TRUE(notMatches("class X { int f(); }; "
1789 "class Y : public X { int f(); };",
1790 methodDecl(isOverride())));
1791 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1792 methodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001793 EXPECT_TRUE(
1794 matches("template <typename Base> struct Y : Base { void f() override;};",
1795 methodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001796}
1797
Manuel Klimek04616e42012-07-06 05:48:52 +00001798TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001799 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001800
1801 EXPECT_TRUE(
1802 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1803 EXPECT_TRUE(
1804 matches("class X { public: X(); }; void x() { X x = X(); }",
1805 Constructor));
1806 EXPECT_TRUE(
1807 matches("class X { public: X(int); }; void x() { X x = 0; }",
1808 Constructor));
1809 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1810}
1811
1812TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001813 StatementMatcher Constructor = constructExpr(
1814 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001815
1816 EXPECT_TRUE(
1817 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1818 Constructor));
1819 EXPECT_TRUE(
1820 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1821 Constructor));
1822 EXPECT_TRUE(
1823 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1824 Constructor));
1825 EXPECT_TRUE(
1826 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1827 Constructor));
1828
Daniel Jasper848cbe12012-09-18 13:09:13 +00001829 StatementMatcher WrongIndex = constructExpr(
1830 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001831 EXPECT_TRUE(
1832 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1833 WrongIndex));
1834}
1835
1836TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001837 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001838
1839 EXPECT_TRUE(
1840 matches("class X { public: X(int); }; void x() { X x(0); }",
1841 Constructor1Arg));
1842 EXPECT_TRUE(
1843 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1844 Constructor1Arg));
1845 EXPECT_TRUE(
1846 matches("class X { public: X(int); }; void x() { X x = 0; }",
1847 Constructor1Arg));
1848 EXPECT_TRUE(
1849 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1850 Constructor1Arg));
1851}
1852
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001853TEST(Matcher, ConstructorListInitialization) {
1854 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1855
1856 EXPECT_TRUE(
1857 matches("class X { public: X(int); }; void x() { X x{0}; }",
1858 ConstructorListInit));
1859 EXPECT_FALSE(
1860 matches("class X { public: X(int); }; void x() { X x(0); }",
1861 ConstructorListInit));
1862}
1863
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001864TEST(Matcher,ThisExpr) {
1865 EXPECT_TRUE(
1866 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1867 EXPECT_TRUE(
1868 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1869}
1870
Manuel Klimek04616e42012-07-06 05:48:52 +00001871TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001872 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001873
1874 std::string ClassString = "class string { public: string(); ~string(); }; ";
1875
1876 EXPECT_TRUE(
1877 matches(ClassString +
1878 "string GetStringByValue();"
1879 "void FunctionTakesString(string s);"
1880 "void run() { FunctionTakesString(GetStringByValue()); }",
1881 TempExpression));
1882
1883 EXPECT_TRUE(
1884 notMatches(ClassString +
1885 "string* GetStringPointer(); "
1886 "void FunctionTakesStringPtr(string* s);"
1887 "void run() {"
1888 " string* s = GetStringPointer();"
1889 " FunctionTakesStringPtr(GetStringPointer());"
1890 " FunctionTakesStringPtr(s);"
1891 "}",
1892 TempExpression));
1893
1894 EXPECT_TRUE(
1895 notMatches("class no_dtor {};"
1896 "no_dtor GetObjByValue();"
1897 "void ConsumeObj(no_dtor param);"
1898 "void run() { ConsumeObj(GetObjByValue()); }",
1899 TempExpression));
1900}
1901
Sam Panzer68a35af2012-08-24 22:04:44 +00001902TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1903 std::string ClassString =
1904 "class string { public: string(); int length(); }; ";
1905
1906 EXPECT_TRUE(
1907 matches(ClassString +
1908 "string GetStringByValue();"
1909 "void FunctionTakesString(string s);"
1910 "void run() { FunctionTakesString(GetStringByValue()); }",
1911 materializeTemporaryExpr()));
1912
1913 EXPECT_TRUE(
1914 notMatches(ClassString +
1915 "string* GetStringPointer(); "
1916 "void FunctionTakesStringPtr(string* s);"
1917 "void run() {"
1918 " string* s = GetStringPointer();"
1919 " FunctionTakesStringPtr(GetStringPointer());"
1920 " FunctionTakesStringPtr(s);"
1921 "}",
1922 materializeTemporaryExpr()));
1923
1924 EXPECT_TRUE(
1925 notMatches(ClassString +
1926 "string GetStringByValue();"
1927 "void run() { int k = GetStringByValue().length(); }",
1928 materializeTemporaryExpr()));
1929
1930 EXPECT_TRUE(
1931 notMatches(ClassString +
1932 "string GetStringByValue();"
1933 "void run() { GetStringByValue(); }",
1934 materializeTemporaryExpr()));
1935}
1936
Manuel Klimek04616e42012-07-06 05:48:52 +00001937TEST(ConstructorDeclaration, SimpleCase) {
1938 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001939 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001940 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001941 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001942}
1943
1944TEST(ConstructorDeclaration, IsImplicit) {
1945 // This one doesn't match because the constructor is not added by the
1946 // compiler (it is not needed).
1947 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001948 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001949 // The compiler added the implicit default constructor.
1950 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001951 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001952 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001953 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001954 // The compiler added an implicit assignment operator.
1955 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1956 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001957}
1958
Daniel Jasper1dad1832012-07-10 20:20:19 +00001959TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1960 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001961 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001962}
1963
1964TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001965 EXPECT_TRUE(notMatches("class Foo {};",
1966 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001967}
1968
Manuel Klimek04616e42012-07-06 05:48:52 +00001969TEST(HasAnyConstructorInitializer, SimpleCase) {
1970 EXPECT_TRUE(notMatches(
1971 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001972 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001973 EXPECT_TRUE(matches(
1974 "class Foo {"
1975 " Foo() : foo_() { }"
1976 " int foo_;"
1977 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001978 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001979}
1980
1981TEST(HasAnyConstructorInitializer, ForField) {
1982 static const char Code[] =
1983 "class Baz { };"
1984 "class Foo {"
1985 " Foo() : foo_() { }"
1986 " Baz foo_;"
1987 " Baz bar_;"
1988 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001989 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1990 forField(hasType(recordDecl(hasName("Baz"))))))));
1991 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001992 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001993 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1994 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001995}
1996
1997TEST(HasAnyConstructorInitializer, WithInitializer) {
1998 static const char Code[] =
1999 "class Foo {"
2000 " Foo() : foo_(0) { }"
2001 " int foo_;"
2002 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002003 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002004 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002005 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002006 withInitializer(integerLiteral(equals(1)))))));
2007}
2008
2009TEST(HasAnyConstructorInitializer, IsWritten) {
2010 static const char Code[] =
2011 "struct Bar { Bar(){} };"
2012 "class Foo {"
2013 " Foo() : foo_() { }"
2014 " Bar foo_;"
2015 " Bar bar_;"
2016 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002017 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002018 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002019 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002020 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002021 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002022 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2023}
2024
2025TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002026 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002027
2028 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2029 EXPECT_TRUE(
2030 matches("class X { public: X(); }; void x() { new X(); }", New));
2031 EXPECT_TRUE(
2032 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2033 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2034}
2035
2036TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002037 StatementMatcher New = constructExpr(
2038 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002039
2040 EXPECT_TRUE(
2041 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2042 New));
2043 EXPECT_TRUE(
2044 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2045 New));
2046 EXPECT_TRUE(
2047 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2048 New));
2049
Daniel Jasper848cbe12012-09-18 13:09:13 +00002050 StatementMatcher WrongIndex = constructExpr(
2051 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002052 EXPECT_TRUE(
2053 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2054 WrongIndex));
2055}
2056
2057TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002058 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002059
2060 EXPECT_TRUE(
2061 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2062 EXPECT_TRUE(
2063 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2064 New));
2065}
2066
Daniel Jasper1dad1832012-07-10 20:20:19 +00002067TEST(Matcher, DeleteExpression) {
2068 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002069 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002070}
2071
Manuel Klimek04616e42012-07-06 05:48:52 +00002072TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002073 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002074
2075 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2076 EXPECT_TRUE(
2077 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2078 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2079}
2080
2081TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002082 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002083 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2084 // wide string
2085 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2086 // with escaped characters
2087 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2088 // no matching -- though the data type is the same, there is no string literal
2089 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2090}
2091
2092TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002093 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002094 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2095 // wide character
2096 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2097 // wide character, Hex encoded, NOT MATCHED!
2098 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2099 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2100}
2101
2102TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002103 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002104 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2105 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2106 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2107 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2108
2109 // Non-matching cases (character literals, float and double)
2110 EXPECT_TRUE(notMatches("int i = L'a';",
2111 HasIntLiteral)); // this is actually a character
2112 // literal cast to int
2113 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2114 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2115 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2116}
2117
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002118TEST(Matcher, FloatLiterals) {
2119 StatementMatcher HasFloatLiteral = floatLiteral();
2120 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2121 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2122 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2123 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2124 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002125 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2126 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2127 EXPECT_TRUE(
2128 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002129
2130 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002131 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2132 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2133 EXPECT_TRUE(
2134 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002135}
2136
Daniel Jasper5901e472012-10-01 13:40:41 +00002137TEST(Matcher, NullPtrLiteral) {
2138 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2139}
2140
Daniel Jasper87c3d362012-09-20 14:12:57 +00002141TEST(Matcher, AsmStatement) {
2142 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2143}
2144
Manuel Klimek04616e42012-07-06 05:48:52 +00002145TEST(Matcher, Conditions) {
2146 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2147
2148 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2149 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2150 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2151 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2152 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2153}
2154
Manuel Klimek909b5c942014-05-27 10:04:12 +00002155TEST(IfStmt, ChildTraversalMatchers) {
2156 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2157 ifStmt(hasThen(boolLiteral(equals(true))))));
2158 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2159 ifStmt(hasThen(boolLiteral(equals(true))))));
2160 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2161 ifStmt(hasElse(boolLiteral(equals(true))))));
2162 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2163 ifStmt(hasElse(boolLiteral(equals(true))))));
2164}
2165
Manuel Klimek04616e42012-07-06 05:48:52 +00002166TEST(MatchBinaryOperator, HasOperatorName) {
2167 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2168
2169 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2170 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2171}
2172
2173TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2174 StatementMatcher OperatorTrueFalse =
2175 binaryOperator(hasLHS(boolLiteral(equals(true))),
2176 hasRHS(boolLiteral(equals(false))));
2177
2178 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2179 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2180 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2181}
2182
2183TEST(MatchBinaryOperator, HasEitherOperand) {
2184 StatementMatcher HasOperand =
2185 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2186
2187 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2188 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2189 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2190}
2191
2192TEST(Matcher, BinaryOperatorTypes) {
2193 // Integration test that verifies the AST provides all binary operators in
2194 // a way we expect.
2195 // FIXME: Operator ','
2196 EXPECT_TRUE(
2197 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2198 EXPECT_TRUE(
2199 matches("bool b; bool c = (b = true);",
2200 binaryOperator(hasOperatorName("="))));
2201 EXPECT_TRUE(
2202 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2203 EXPECT_TRUE(
2204 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2205 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2206 EXPECT_TRUE(
2207 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2208 EXPECT_TRUE(
2209 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2210 EXPECT_TRUE(
2211 matches("int i = 1; int j = (i <<= 2);",
2212 binaryOperator(hasOperatorName("<<="))));
2213 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2214 EXPECT_TRUE(
2215 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2216 EXPECT_TRUE(
2217 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2218 EXPECT_TRUE(
2219 matches("int i = 1; int j = (i >>= 2);",
2220 binaryOperator(hasOperatorName(">>="))));
2221 EXPECT_TRUE(
2222 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2223 EXPECT_TRUE(
2224 matches("int i = 42; int j = (i ^= 42);",
2225 binaryOperator(hasOperatorName("^="))));
2226 EXPECT_TRUE(
2227 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2228 EXPECT_TRUE(
2229 matches("int i = 42; int j = (i %= 42);",
2230 binaryOperator(hasOperatorName("%="))));
2231 EXPECT_TRUE(
2232 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2233 EXPECT_TRUE(
2234 matches("bool b = true && false;",
2235 binaryOperator(hasOperatorName("&&"))));
2236 EXPECT_TRUE(
2237 matches("bool b = true; bool c = (b &= false);",
2238 binaryOperator(hasOperatorName("&="))));
2239 EXPECT_TRUE(
2240 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2241 EXPECT_TRUE(
2242 matches("bool b = true || false;",
2243 binaryOperator(hasOperatorName("||"))));
2244 EXPECT_TRUE(
2245 matches("bool b = true; bool c = (b |= false);",
2246 binaryOperator(hasOperatorName("|="))));
2247 EXPECT_TRUE(
2248 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2249 EXPECT_TRUE(
2250 matches("int i = 42; int j = (i *= 23);",
2251 binaryOperator(hasOperatorName("*="))));
2252 EXPECT_TRUE(
2253 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2254 EXPECT_TRUE(
2255 matches("int i = 42; int j = (i /= 23);",
2256 binaryOperator(hasOperatorName("/="))));
2257 EXPECT_TRUE(
2258 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2259 EXPECT_TRUE(
2260 matches("int i = 42; int j = (i += 23);",
2261 binaryOperator(hasOperatorName("+="))));
2262 EXPECT_TRUE(
2263 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2264 EXPECT_TRUE(
2265 matches("int i = 42; int j = (i -= 23);",
2266 binaryOperator(hasOperatorName("-="))));
2267 EXPECT_TRUE(
2268 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2269 binaryOperator(hasOperatorName("->*"))));
2270 EXPECT_TRUE(
2271 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2272 binaryOperator(hasOperatorName(".*"))));
2273
2274 // Member expressions as operators are not supported in matches.
2275 EXPECT_TRUE(
2276 notMatches("struct A { void x(A *a) { a->x(this); } };",
2277 binaryOperator(hasOperatorName("->"))));
2278
2279 // Initializer assignments are not represented as operator equals.
2280 EXPECT_TRUE(
2281 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2282
2283 // Array indexing is not represented as operator.
2284 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2285
2286 // Overloaded operators do not match at all.
2287 EXPECT_TRUE(notMatches(
2288 "struct A { bool operator&&(const A &a) const { return false; } };"
2289 "void x() { A a, b; a && b; }",
2290 binaryOperator()));
2291}
2292
2293TEST(MatchUnaryOperator, HasOperatorName) {
2294 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2295
2296 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2297 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2298}
2299
2300TEST(MatchUnaryOperator, HasUnaryOperand) {
2301 StatementMatcher OperatorOnFalse =
2302 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2303
2304 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2305 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2306}
2307
2308TEST(Matcher, UnaryOperatorTypes) {
2309 // Integration test that verifies the AST provides all unary operators in
2310 // a way we expect.
2311 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2312 EXPECT_TRUE(
2313 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2314 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2315 EXPECT_TRUE(
2316 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2317 EXPECT_TRUE(
2318 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2319 EXPECT_TRUE(
2320 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2321 EXPECT_TRUE(
2322 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2323 EXPECT_TRUE(
2324 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2325 EXPECT_TRUE(
2326 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2327 EXPECT_TRUE(
2328 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2329
2330 // We don't match conversion operators.
2331 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2332
2333 // Function calls are not represented as operator.
2334 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2335
2336 // Overloaded operators do not match at all.
2337 // FIXME: We probably want to add that.
2338 EXPECT_TRUE(notMatches(
2339 "struct A { bool operator!() const { return false; } };"
2340 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2341}
2342
2343TEST(Matcher, ConditionalOperator) {
2344 StatementMatcher Conditional = conditionalOperator(
2345 hasCondition(boolLiteral(equals(true))),
2346 hasTrueExpression(boolLiteral(equals(false))));
2347
2348 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2349 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2350 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2351
2352 StatementMatcher ConditionalFalse = conditionalOperator(
2353 hasFalseExpression(boolLiteral(equals(false))));
2354
2355 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2356 EXPECT_TRUE(
2357 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2358}
2359
Daniel Jasper1dad1832012-07-10 20:20:19 +00002360TEST(ArraySubscriptMatchers, ArraySubscripts) {
2361 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2362 arraySubscriptExpr()));
2363 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2364 arraySubscriptExpr()));
2365}
2366
2367TEST(ArraySubscriptMatchers, ArrayIndex) {
2368 EXPECT_TRUE(matches(
2369 "int i[2]; void f() { i[1] = 1; }",
2370 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2371 EXPECT_TRUE(matches(
2372 "int i[2]; void f() { 1[i] = 1; }",
2373 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2374 EXPECT_TRUE(notMatches(
2375 "int i[2]; void f() { i[1] = 1; }",
2376 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2377}
2378
2379TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2380 EXPECT_TRUE(matches(
2381 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002382 arraySubscriptExpr(hasBase(implicitCastExpr(
2383 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002384}
2385
Manuel Klimek04616e42012-07-06 05:48:52 +00002386TEST(Matcher, HasNameSupportsNamespaces) {
2387 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002388 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002389 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002390 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002391 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002392 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002393 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002394 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002395 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002396 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002397 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002398 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002399 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002400 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002401 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002402 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002403 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002404 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002405 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002406 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002407 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002408 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002409 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002410 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002411}
2412
2413TEST(Matcher, HasNameSupportsOuterClasses) {
2414 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002415 matches("class A { class B { class C; }; };",
2416 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002417 EXPECT_TRUE(
2418 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002419 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002420 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002421 matches("class A { class B { class C; }; };",
2422 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002423 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002424 matches("class A { class B { class C; }; };",
2425 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002426 EXPECT_TRUE(
2427 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002428 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002429 EXPECT_TRUE(
2430 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002431 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002432 EXPECT_TRUE(
2433 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002434 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002435 EXPECT_TRUE(
2436 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002437 recordDecl(hasName("::C"))));
2438 EXPECT_TRUE(
2439 notMatches("class A { class B { class C; }; };",
2440 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002441 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002442 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002443 EXPECT_TRUE(
2444 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002445 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002446}
2447
2448TEST(Matcher, IsDefinition) {
2449 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002450 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002451 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2452 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2453
2454 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002455 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002456 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2457 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2458
2459 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002460 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002461 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2462 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2463}
2464
2465TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002466 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002467 ofClass(hasName("X")))));
2468
2469 EXPECT_TRUE(
2470 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2471 EXPECT_TRUE(
2472 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2473 Constructor));
2474 EXPECT_TRUE(
2475 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2476 Constructor));
2477}
2478
2479TEST(Matcher, VisitsTemplateInstantiations) {
2480 EXPECT_TRUE(matches(
2481 "class A { public: void x(); };"
2482 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002483 "void f() { B<A> b; b.y(); }",
2484 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002485
2486 EXPECT_TRUE(matches(
2487 "class A { public: void x(); };"
2488 "class C {"
2489 " public:"
2490 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2491 "};"
2492 "void f() {"
2493 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002494 "}",
2495 recordDecl(hasName("C"),
2496 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002497}
2498
Daniel Jasper1dad1832012-07-10 20:20:19 +00002499TEST(Matcher, HandlesNullQualTypes) {
2500 // FIXME: Add a Type matcher so we can replace uses of this
2501 // variable with Type(True())
2502 const TypeMatcher AnyType = anything();
2503
2504 // We don't really care whether this matcher succeeds; we're testing that
2505 // it completes without crashing.
2506 EXPECT_TRUE(matches(
2507 "struct A { };"
2508 "template <typename T>"
2509 "void f(T t) {"
2510 " T local_t(t /* this becomes a null QualType in the AST */);"
2511 "}"
2512 "void g() {"
2513 " f(0);"
2514 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002515 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002516 anyOf(
2517 TypeMatcher(hasDeclaration(anything())),
2518 pointsTo(AnyType),
2519 references(AnyType)
2520 // Other QualType matchers should go here.
2521 ))))));
2522}
2523
Manuel Klimek04616e42012-07-06 05:48:52 +00002524// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002525AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002526 // Make sure all special variables are used: node, match_finder,
2527 // bound_nodes_builder, and the parameter named 'AMatcher'.
2528 return AMatcher.matches(Node, Finder, Builder);
2529}
2530
2531TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002532 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002533
2534 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002535 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002536
2537 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002538 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002539
2540 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002541 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002542}
2543
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002544AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2545 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2546 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002547 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002548 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002549 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2550 ASTMatchFinder::BK_First);
2551}
2552
2553TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002554 DeclarationMatcher HasClassB =
2555 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002556
2557 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002558 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002559
2560 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002561 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002562
2563 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002564 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002565
2566 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002567 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002568
2569 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2570}
2571
2572TEST(For, FindsForLoops) {
2573 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2574 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002575 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2576 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002577 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002578}
2579
Daniel Jasper4e566c42012-07-12 08:50:38 +00002580TEST(For, ForLoopInternals) {
2581 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2582 forStmt(hasCondition(anything()))));
2583 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2584 forStmt(hasLoopInit(anything()))));
2585}
2586
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002587TEST(For, ForRangeLoopInternals) {
2588 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2589 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002590 EXPECT_TRUE(matches(
2591 "void f(){ int a[] {1, 2}; for (int i : a); }",
2592 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002593}
2594
Daniel Jasper4e566c42012-07-12 08:50:38 +00002595TEST(For, NegativeForLoopInternals) {
2596 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002597 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002598 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2599 forStmt(hasLoopInit(anything()))));
2600}
2601
Manuel Klimek04616e42012-07-06 05:48:52 +00002602TEST(For, ReportsNoFalsePositives) {
2603 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2604 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2605}
2606
2607TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002608 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2609 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2610 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002611}
2612
2613TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2614 // It's not a compound statement just because there's "{}" in the source
2615 // text. This is an AST search, not grep.
2616 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002617 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002618 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002619 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002620}
2621
Daniel Jasper4e566c42012-07-12 08:50:38 +00002622TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002623 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002624 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002625 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002626 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002627 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002628 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002629 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002630 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002631 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2632 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002633}
2634
2635TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2636 // The simplest case: every compound statement is in a function
2637 // definition, and the function body itself must be a compound
2638 // statement.
2639 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002640 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002641}
2642
2643TEST(HasAnySubstatement, IsNotRecursive) {
2644 // It's really "has any immediate substatement".
2645 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002646 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002647}
2648
2649TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2650 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002651 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002652}
2653
2654TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2655 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002656 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002657}
2658
2659TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2660 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002661 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002662 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002663 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002664}
2665
2666TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2667 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002668 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002669 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002670 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002671 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002672 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002673}
2674
2675TEST(StatementCountIs, WorksWithMultipleStatements) {
2676 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002677 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002678}
2679
2680TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2681 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002682 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002683 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002684 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002685 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002686 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002687 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002688 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002689}
2690
2691TEST(Member, WorksInSimplestCase) {
2692 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002693 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002694}
2695
2696TEST(Member, DoesNotMatchTheBaseExpression) {
2697 // Don't pick out the wrong part of the member expression, this should
2698 // be checking the member (name) only.
2699 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002700 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002701}
2702
2703TEST(Member, MatchesInMemberFunctionCall) {
2704 EXPECT_TRUE(matches("void f() {"
2705 " struct { void first() {}; } s;"
2706 " s.first();"
2707 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002708 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002709}
2710
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002711TEST(Member, MatchesMember) {
2712 EXPECT_TRUE(matches(
2713 "struct A { int i; }; void f() { A a; a.i = 2; }",
2714 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2715 EXPECT_TRUE(notMatches(
2716 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2717 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2718}
2719
Daniel Jasper639522c2013-02-25 12:02:08 +00002720TEST(Member, UnderstandsAccess) {
2721 EXPECT_TRUE(matches(
2722 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2723 EXPECT_TRUE(notMatches(
2724 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2725 EXPECT_TRUE(notMatches(
2726 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2727
2728 EXPECT_TRUE(notMatches(
2729 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2730 EXPECT_TRUE(notMatches(
2731 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2732 EXPECT_TRUE(matches(
2733 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2734
2735 EXPECT_TRUE(notMatches(
2736 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2737 EXPECT_TRUE(matches("class A { protected: int i; };",
2738 fieldDecl(isProtected(), hasName("i"))));
2739 EXPECT_TRUE(notMatches(
2740 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2741
2742 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2743 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2744 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2745 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2746}
2747
Dmitri Gribenko06963042012-08-18 00:29:27 +00002748TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002749 // Fails in C++11 mode
2750 EXPECT_TRUE(matchesConditionally(
2751 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2752 "class X { void *operator new(std::size_t); };",
2753 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002754
2755 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002756 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002757
Daniel Jasper5901e472012-10-01 13:40:41 +00002758 // Fails in C++11 mode
2759 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002760 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2761 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002762 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002763}
2764
Manuel Klimek04616e42012-07-06 05:48:52 +00002765TEST(HasObjectExpression, DoesNotMatchMember) {
2766 EXPECT_TRUE(notMatches(
2767 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002768 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002769}
2770
2771TEST(HasObjectExpression, MatchesBaseOfVariable) {
2772 EXPECT_TRUE(matches(
2773 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002774 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002775 EXPECT_TRUE(matches(
2776 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002777 memberExpr(hasObjectExpression(
2778 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002779}
2780
2781TEST(HasObjectExpression,
2782 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2783 EXPECT_TRUE(matches(
2784 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002785 memberExpr(hasObjectExpression(
2786 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002787 EXPECT_TRUE(matches(
2788 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002789 memberExpr(hasObjectExpression(
2790 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002791}
2792
2793TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002794 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2795 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2796 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2797 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002798}
2799
2800TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002801 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002802}
2803
2804TEST(IsConstQualified, MatchesConstInt) {
2805 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002806 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002807}
2808
2809TEST(IsConstQualified, MatchesConstPointer) {
2810 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002811 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002812}
2813
2814TEST(IsConstQualified, MatchesThroughTypedef) {
2815 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002816 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002817 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002818 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002819}
2820
2821TEST(IsConstQualified, DoesNotMatchInappropriately) {
2822 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002823 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002824 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002825 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002826}
2827
Sam Panzer80c13772012-08-16 16:58:10 +00002828TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002829 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2830 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2831 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2832 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002833}
2834TEST(CastExpression, MatchesImplicitCasts) {
2835 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002836 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002837 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002838 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002839}
2840
2841TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002842 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2843 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2844 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2845 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002846}
2847
Manuel Klimek04616e42012-07-06 05:48:52 +00002848TEST(ReinterpretCast, MatchesSimpleCase) {
2849 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002850 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002851}
2852
2853TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002854 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002855 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002856 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002857 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002858 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002859 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2860 "B b;"
2861 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002862 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002863}
2864
2865TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002866 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002867 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002868 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002869}
2870
2871TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002872 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002873 EXPECT_TRUE(
2874 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002875 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002876 EXPECT_TRUE(
2877 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002878 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002879}
2880
2881TEST(DynamicCast, MatchesSimpleCase) {
2882 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2883 "B b;"
2884 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002885 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002886}
2887
2888TEST(StaticCast, MatchesSimpleCase) {
2889 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002890 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002891}
2892
2893TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002894 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002895 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002896 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002897 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002898 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002899 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2900 "B b;"
2901 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002902 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002903}
2904
Daniel Jasper417f7762012-09-18 13:36:17 +00002905TEST(CStyleCast, MatchesSimpleCase) {
2906 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2907}
2908
2909TEST(CStyleCast, DoesNotMatchOtherCasts) {
2910 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2911 "char q, *r = const_cast<char*>(&q);"
2912 "void* s = reinterpret_cast<char*>(&s);"
2913 "struct B { virtual ~B() {} }; struct D : B {};"
2914 "B b;"
2915 "D* t = dynamic_cast<D*>(&b);",
2916 cStyleCastExpr()));
2917}
2918
Manuel Klimek04616e42012-07-06 05:48:52 +00002919TEST(HasDestinationType, MatchesSimpleCase) {
2920 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002921 staticCastExpr(hasDestinationType(
2922 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002923}
2924
Sam Panzer80c13772012-08-16 16:58:10 +00002925TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2926 // This test creates an implicit const cast.
2927 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002928 implicitCastExpr(
2929 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002930 // This test creates an implicit array-to-pointer cast.
2931 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002932 implicitCastExpr(hasImplicitDestinationType(
2933 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002934}
2935
2936TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2937 // This test creates an implicit cast from int to char.
2938 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002939 implicitCastExpr(hasImplicitDestinationType(
2940 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002941 // This test creates an implicit array-to-pointer cast.
2942 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002943 implicitCastExpr(hasImplicitDestinationType(
2944 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002945}
2946
2947TEST(ImplicitCast, MatchesSimpleCase) {
2948 // This test creates an implicit const cast.
2949 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002950 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002951 // This test creates an implicit cast from int to char.
2952 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002953 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002954 // This test creates an implicit array-to-pointer cast.
2955 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002956 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002957}
2958
2959TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002960 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002961 // are present, and that it ignores explicit and paren casts.
2962
2963 // These two test cases have no casts.
2964 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002965 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002966 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002967 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002968
2969 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002970 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002971 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002972 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002973
2974 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002975 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002976}
2977
2978TEST(IgnoringImpCasts, MatchesImpCasts) {
2979 // This test checks that ignoringImpCasts matches when implicit casts are
2980 // present and its inner matcher alone does not match.
2981 // Note that this test creates an implicit const cast.
2982 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002983 varDecl(hasInitializer(ignoringImpCasts(
2984 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002985 // This test creates an implict cast from int to char.
2986 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002987 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002988 integerLiteral(equals(0)))))));
2989}
2990
2991TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2992 // These tests verify that ignoringImpCasts does not match if the inner
2993 // matcher does not match.
2994 // Note that the first test creates an implicit const cast.
2995 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002996 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002997 unless(anything()))))));
2998 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002999 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003000 unless(anything()))))));
3001
3002 // These tests verify that ignoringImplictCasts does not look through explicit
3003 // casts or parentheses.
3004 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003005 varDecl(hasInitializer(ignoringImpCasts(
3006 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003007 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003008 varDecl(hasInitializer(ignoringImpCasts(
3009 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003010 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003011 varDecl(hasInitializer(ignoringImpCasts(
3012 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003013 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003014 varDecl(hasInitializer(ignoringImpCasts(
3015 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003016}
3017
3018TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3019 // This test verifies that expressions that do not have implicit casts
3020 // still match the inner matcher.
3021 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003022 varDecl(hasInitializer(ignoringImpCasts(
3023 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003024}
3025
3026TEST(IgnoringParenCasts, MatchesParenCasts) {
3027 // This test checks that ignoringParenCasts matches when parentheses and/or
3028 // casts are present and its inner matcher alone does not match.
3029 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003030 varDecl(hasInitializer(ignoringParenCasts(
3031 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003032 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003033 varDecl(hasInitializer(ignoringParenCasts(
3034 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003035
3036 // This test creates an implict cast from int to char in addition to the
3037 // parentheses.
3038 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003039 varDecl(hasInitializer(ignoringParenCasts(
3040 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003041
3042 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003043 varDecl(hasInitializer(ignoringParenCasts(
3044 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003045 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003046 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003047 integerLiteral(equals(0)))))));
3048}
3049
3050TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3051 // This test verifies that expressions that do not have any casts still match.
3052 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003053 varDecl(hasInitializer(ignoringParenCasts(
3054 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003055}
3056
3057TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3058 // These tests verify that ignoringImpCasts does not match if the inner
3059 // matcher does not match.
3060 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003061 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003062 unless(anything()))))));
3063
3064 // This test creates an implicit cast from int to char in addition to the
3065 // parentheses.
3066 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003067 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003068 unless(anything()))))));
3069
3070 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003071 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003072 unless(anything()))))));
3073}
3074
3075TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3076 // This test checks that ignoringParenAndImpCasts matches when
3077 // parentheses and/or implicit casts are present and its inner matcher alone
3078 // does not match.
3079 // Note that this test creates an implicit const cast.
3080 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003081 varDecl(hasInitializer(ignoringParenImpCasts(
3082 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003083 // This test creates an implicit cast from int to char.
3084 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003085 varDecl(hasInitializer(ignoringParenImpCasts(
3086 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003087}
3088
3089TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3090 // This test verifies that expressions that do not have parentheses or
3091 // implicit casts still match.
3092 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003093 varDecl(hasInitializer(ignoringParenImpCasts(
3094 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003095 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003096 varDecl(hasInitializer(ignoringParenImpCasts(
3097 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003098}
3099
3100TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3101 // These tests verify that ignoringParenImpCasts does not match if
3102 // the inner matcher does not match.
3103 // This test creates an implicit cast.
3104 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003105 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003106 unless(anything()))))));
3107 // These tests verify that ignoringParenAndImplictCasts does not look
3108 // through explicit casts.
3109 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003110 varDecl(hasInitializer(ignoringParenImpCasts(
3111 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003112 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003113 varDecl(hasInitializer(ignoringParenImpCasts(
3114 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003115 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003116 varDecl(hasInitializer(ignoringParenImpCasts(
3117 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003118}
3119
Manuel Klimeke9235692012-07-25 10:02:02 +00003120TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003121 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3122 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003123 implicitCastExpr(
3124 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003125}
3126
Manuel Klimeke9235692012-07-25 10:02:02 +00003127TEST(HasSourceExpression, MatchesExplicitCasts) {
3128 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003129 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003130 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003131 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003132}
3133
Manuel Klimek04616e42012-07-06 05:48:52 +00003134TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003135 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003136}
3137
3138TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003139 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003140}
3141
3142TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003143 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003144}
3145
3146TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003147 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003148}
3149
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003150TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3151 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3152 "const Foo f = Foo();",
3153 varDecl(hasInitializer(exprWithCleanups()))));
3154 EXPECT_FALSE(matches("struct Foo { };"
3155 "const Foo f = Foo();",
3156 varDecl(hasInitializer(exprWithCleanups()))));
3157}
3158
Daniel Jasper1dad1832012-07-10 20:20:19 +00003159TEST(InitListExpression, MatchesInitListExpression) {
3160 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3161 initListExpr(hasType(asString("int [2]")))));
3162 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003163 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003164 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3165 "void f();"
3166 "S s[1] = { &f };",
3167 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003168 EXPECT_TRUE(
3169 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003170}
3171
3172TEST(UsingDeclaration, MatchesUsingDeclarations) {
3173 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3174 usingDecl()));
3175}
3176
3177TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3178 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3179 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3180}
3181
3182TEST(UsingDeclaration, MatchesSpecificTarget) {
3183 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3184 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003185 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003186 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3187 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003188 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003189}
3190
3191TEST(UsingDeclaration, ThroughUsingDeclaration) {
3192 EXPECT_TRUE(matches(
3193 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003194 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003195 EXPECT_TRUE(notMatches(
3196 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003197 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003198}
3199
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003200TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3201 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3202 usingDirectiveDecl()));
3203 EXPECT_FALSE(
3204 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3205}
3206
Sam Panzerd624bfb2012-08-16 17:20:59 +00003207TEST(SingleDecl, IsSingleDecl) {
3208 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003209 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003210 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3211 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3212 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3213 SingleDeclStmt));
3214}
3215
3216TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003217 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003218
3219 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003220 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003221 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003222 declStmt(containsDeclaration(0, MatchesInit),
3223 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003224 unsigned WrongIndex = 42;
3225 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003226 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003227 MatchesInit))));
3228}
3229
3230TEST(DeclCount, DeclCountIsCorrect) {
3231 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003232 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003233 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003234 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003235 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003236 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003237}
3238
Manuel Klimek04616e42012-07-06 05:48:52 +00003239TEST(While, MatchesWhileLoops) {
3240 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3241 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3242 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3243}
3244
3245TEST(Do, MatchesDoLoops) {
3246 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3247 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3248}
3249
3250TEST(Do, DoesNotMatchWhileLoops) {
3251 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3252}
3253
3254TEST(SwitchCase, MatchesCase) {
3255 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3256 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3257 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3258 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3259}
3260
Daniel Jasper87c3d362012-09-20 14:12:57 +00003261TEST(SwitchCase, MatchesSwitch) {
3262 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3263 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3264 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3265 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3266}
3267
Peter Collingbourne3154a102013-05-10 11:52:02 +00003268TEST(SwitchCase, MatchesEachCase) {
3269 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3270 switchStmt(forEachSwitchCase(caseStmt()))));
3271 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3272 switchStmt(forEachSwitchCase(caseStmt()))));
3273 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3274 switchStmt(forEachSwitchCase(caseStmt()))));
3275 EXPECT_TRUE(notMatches(
3276 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3277 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3278 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3279 switchStmt(forEachSwitchCase(
3280 caseStmt(hasCaseConstant(integerLiteral()))))));
3281 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3282 switchStmt(forEachSwitchCase(
3283 caseStmt(hasCaseConstant(integerLiteral()))))));
3284 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3285 switchStmt(forEachSwitchCase(
3286 caseStmt(hasCaseConstant(integerLiteral()))))));
3287 EXPECT_TRUE(matchAndVerifyResultTrue(
3288 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3289 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3290 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3291}
3292
Manuel Klimekba46fc02013-07-19 11:50:54 +00003293TEST(ForEachConstructorInitializer, MatchesInitializers) {
3294 EXPECT_TRUE(matches(
3295 "struct X { X() : i(42), j(42) {} int i, j; };",
3296 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3297}
3298
Daniel Jasper87c3d362012-09-20 14:12:57 +00003299TEST(ExceptionHandling, SimpleCases) {
3300 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3301 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3302 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3303 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3304 throwExpr()));
3305 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3306 throwExpr()));
3307}
3308
Manuel Klimek04616e42012-07-06 05:48:52 +00003309TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3310 EXPECT_TRUE(notMatches(
3311 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003312 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003313 EXPECT_TRUE(notMatches(
3314 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003315 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003316}
3317
3318TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3319 EXPECT_TRUE(matches(
3320 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003321 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003322}
3323
3324TEST(ForEach, BindsOneNode) {
3325 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003326 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003327 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003328}
3329
3330TEST(ForEach, BindsMultipleNodes) {
3331 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003332 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003333 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003334}
3335
3336TEST(ForEach, BindsRecursiveCombinations) {
3337 EXPECT_TRUE(matchAndVerifyResultTrue(
3338 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003339 recordDecl(hasName("C"),
3340 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003341 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003342}
3343
3344TEST(ForEachDescendant, BindsOneNode) {
3345 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003346 recordDecl(hasName("C"),
3347 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003348 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003349}
3350
Daniel Jasper94a56852012-11-16 18:39:22 +00003351TEST(ForEachDescendant, NestedForEachDescendant) {
3352 DeclarationMatcher m = recordDecl(
3353 isDefinition(), decl().bind("x"), hasName("C"));
3354 EXPECT_TRUE(matchAndVerifyResultTrue(
3355 "class A { class B { class C {}; }; };",
3356 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3357 new VerifyIdIsBoundTo<Decl>("x", "C")));
3358
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003359 // Check that a partial match of 'm' that binds 'x' in the
3360 // first part of anyOf(m, anything()) will not overwrite the
3361 // binding created by the earlier binding in the hasDescendant.
3362 EXPECT_TRUE(matchAndVerifyResultTrue(
3363 "class A { class B { class C {}; }; };",
3364 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3365 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003366}
3367
Manuel Klimek04616e42012-07-06 05:48:52 +00003368TEST(ForEachDescendant, BindsMultipleNodes) {
3369 EXPECT_TRUE(matchAndVerifyResultTrue(
3370 "class C { class D { int x; int y; }; "
3371 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003372 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003373 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003374}
3375
3376TEST(ForEachDescendant, BindsRecursiveCombinations) {
3377 EXPECT_TRUE(matchAndVerifyResultTrue(
3378 "class C { class D { "
3379 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003380 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3381 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003382 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003383}
3384
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003385TEST(ForEachDescendant, BindsCombinations) {
3386 EXPECT_TRUE(matchAndVerifyResultTrue(
3387 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3388 "(true) {} }",
3389 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3390 forEachDescendant(whileStmt().bind("while"))),
3391 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3392}
3393
3394TEST(Has, DoesNotDeleteBindings) {
3395 EXPECT_TRUE(matchAndVerifyResultTrue(
3396 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3397 new VerifyIdIsBoundTo<Decl>("x", 1)));
3398}
3399
3400TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3401 // Those matchers cover all the cases where an inner matcher is called
3402 // and there is not a 1:1 relationship between the match of the outer
3403 // matcher and the match of the inner matcher.
3404 // The pattern to look for is:
3405 // ... return InnerMatcher.matches(...); ...
3406 // In which case no special handling is needed.
3407 //
3408 // On the other hand, if there are multiple alternative matches
3409 // (for example forEach*) or matches might be discarded (for example has*)
3410 // the implementation must make sure that the discarded matches do not
3411 // affect the bindings.
3412 // When new such matchers are added, add a test here that:
3413 // - matches a simple node, and binds it as the first thing in the matcher:
3414 // recordDecl(decl().bind("x"), hasName("X")))
3415 // - uses the matcher under test afterwards in a way that not the first
3416 // alternative is matched; for anyOf, that means the first branch
3417 // would need to return false; for hasAncestor, it means that not
3418 // the direct parent matches the inner matcher.
3419
3420 EXPECT_TRUE(matchAndVerifyResultTrue(
3421 "class X { int y; };",
3422 recordDecl(
3423 recordDecl().bind("x"), hasName("::X"),
3424 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3425 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3426 EXPECT_TRUE(matchAndVerifyResultTrue(
3427 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3428 anyOf(unless(anything()), anything())),
3429 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3430 EXPECT_TRUE(matchAndVerifyResultTrue(
3431 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3432 classTemplateSpecializationDecl(
3433 decl().bind("x"),
3434 hasAnyTemplateArgument(refersToType(asString("int")))),
3435 new VerifyIdIsBoundTo<Decl>("x", 1)));
3436 EXPECT_TRUE(matchAndVerifyResultTrue(
3437 "class X { void f(); void g(); };",
3438 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3439 new VerifyIdIsBoundTo<Decl>("x", 1)));
3440 EXPECT_TRUE(matchAndVerifyResultTrue(
3441 "class X { X() : a(1), b(2) {} double a; int b; };",
3442 recordDecl(decl().bind("x"),
3443 has(constructorDecl(
3444 hasAnyConstructorInitializer(forField(hasName("b")))))),
3445 new VerifyIdIsBoundTo<Decl>("x", 1)));
3446 EXPECT_TRUE(matchAndVerifyResultTrue(
3447 "void x(int, int) { x(0, 42); }",
3448 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3449 new VerifyIdIsBoundTo<Expr>("x", 1)));
3450 EXPECT_TRUE(matchAndVerifyResultTrue(
3451 "void x(int, int y) {}",
3452 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3453 new VerifyIdIsBoundTo<Decl>("x", 1)));
3454 EXPECT_TRUE(matchAndVerifyResultTrue(
3455 "void x() { return; if (true) {} }",
3456 functionDecl(decl().bind("x"),
3457 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3458 new VerifyIdIsBoundTo<Decl>("x", 1)));
3459 EXPECT_TRUE(matchAndVerifyResultTrue(
3460 "namespace X { void b(int); void b(); }"
3461 "using X::b;",
3462 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3463 functionDecl(parameterCountIs(1))))),
3464 new VerifyIdIsBoundTo<Decl>("x", 1)));
3465 EXPECT_TRUE(matchAndVerifyResultTrue(
3466 "class A{}; class B{}; class C : B, A {};",
3467 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3468 new VerifyIdIsBoundTo<Decl>("x", 1)));
3469 EXPECT_TRUE(matchAndVerifyResultTrue(
3470 "class A{}; typedef A B; typedef A C; typedef A D;"
3471 "class E : A {};",
3472 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3473 new VerifyIdIsBoundTo<Decl>("x", 1)));
3474 EXPECT_TRUE(matchAndVerifyResultTrue(
3475 "class A { class B { void f() {} }; };",
3476 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3477 new VerifyIdIsBoundTo<Decl>("x", 1)));
3478 EXPECT_TRUE(matchAndVerifyResultTrue(
3479 "template <typename T> struct A { struct B {"
3480 " void f() { if(true) {} }"
3481 "}; };"
3482 "void t() { A<int>::B b; b.f(); }",
3483 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3484 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3485 EXPECT_TRUE(matchAndVerifyResultTrue(
3486 "class A {};",
3487 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3488 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003489 EXPECT_TRUE(matchAndVerifyResultTrue(
3490 "class A { A() : s(), i(42) {} const char *s; int i; };",
3491 constructorDecl(hasName("::A::A"), decl().bind("x"),
3492 forEachConstructorInitializer(forField(hasName("i")))),
3493 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003494}
3495
Daniel Jasper33806cd2012-11-11 22:14:55 +00003496TEST(ForEachDescendant, BindsCorrectNodes) {
3497 EXPECT_TRUE(matchAndVerifyResultTrue(
3498 "class C { void f(); int i; };",
3499 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3500 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3501 EXPECT_TRUE(matchAndVerifyResultTrue(
3502 "class C { void f() {} int i; };",
3503 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3504 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3505}
3506
Manuel Klimekabf43712013-02-04 10:59:20 +00003507TEST(FindAll, BindsNodeOnMatch) {
3508 EXPECT_TRUE(matchAndVerifyResultTrue(
3509 "class A {};",
3510 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3511 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3512}
3513
3514TEST(FindAll, BindsDescendantNodeOnMatch) {
3515 EXPECT_TRUE(matchAndVerifyResultTrue(
3516 "class A { int a; int b; };",
3517 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3518 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3519}
3520
3521TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3522 EXPECT_TRUE(matchAndVerifyResultTrue(
3523 "class A { int a; int b; };",
3524 recordDecl(hasName("::A"),
3525 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3526 fieldDecl().bind("v"))))),
3527 new VerifyIdIsBoundTo<Decl>("v", 3)));
3528
3529 EXPECT_TRUE(matchAndVerifyResultTrue(
3530 "class A { class B {}; class C {}; };",
3531 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3532 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3533}
3534
Manuel Klimek88b95872013-02-04 09:42:38 +00003535TEST(EachOf, TriggersForEachMatch) {
3536 EXPECT_TRUE(matchAndVerifyResultTrue(
3537 "class A { int a; int b; };",
3538 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3539 has(fieldDecl(hasName("b")).bind("v")))),
3540 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3541}
3542
3543TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3544 EXPECT_TRUE(matchAndVerifyResultTrue(
3545 "class A { int a; int c; };",
3546 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3547 has(fieldDecl(hasName("b")).bind("v")))),
3548 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3549 EXPECT_TRUE(matchAndVerifyResultTrue(
3550 "class A { int c; int b; };",
3551 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3552 has(fieldDecl(hasName("b")).bind("v")))),
3553 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3554 EXPECT_TRUE(notMatches(
3555 "class A { int c; int d; };",
3556 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3557 has(fieldDecl(hasName("b")).bind("v"))))));
3558}
Manuel Klimek04616e42012-07-06 05:48:52 +00003559
3560TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3561 // Make sure that we can both match the class by name (::X) and by the type
3562 // the template was instantiated with (via a field).
3563
3564 EXPECT_TRUE(matches(
3565 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003566 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003567
3568 EXPECT_TRUE(matches(
3569 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003570 recordDecl(isTemplateInstantiation(), hasDescendant(
3571 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003572}
3573
3574TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3575 EXPECT_TRUE(matches(
3576 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003577 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003578 isTemplateInstantiation())));
3579}
3580
3581TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3582 EXPECT_TRUE(matches(
3583 "template <typename T> class X { T t; }; class A {};"
3584 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003585 recordDecl(isTemplateInstantiation(), hasDescendant(
3586 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003587}
3588
3589TEST(IsTemplateInstantiation,
3590 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3591 EXPECT_TRUE(matches(
3592 "template <typename T> class X {};"
3593 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003594 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003595}
3596
3597TEST(IsTemplateInstantiation,
3598 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3599 EXPECT_TRUE(matches(
3600 "class A {};"
3601 "class X {"
3602 " template <typename U> class Y { U u; };"
3603 " Y<A> y;"
3604 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003605 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003606}
3607
3608TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3609 // FIXME: Figure out whether this makes sense. It doesn't affect the
3610 // normal use case as long as the uppermost instantiation always is marked
3611 // as template instantiation, but it might be confusing as a predicate.
3612 EXPECT_TRUE(matches(
3613 "class A {};"
3614 "template <typename T> class X {"
3615 " template <typename U> class Y { U u; };"
3616 " Y<T> y;"
3617 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003618 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003619}
3620
3621TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3622 EXPECT_TRUE(notMatches(
3623 "template <typename T> class X {}; class A {};"
3624 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003625 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003626}
3627
3628TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3629 EXPECT_TRUE(notMatches(
3630 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003631 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003632}
3633
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003634TEST(IsInstantiated, MatchesInstantiation) {
3635 EXPECT_TRUE(
3636 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3637 recordDecl(isInstantiated())));
3638}
3639
3640TEST(IsInstantiated, NotMatchesDefinition) {
3641 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3642 recordDecl(isInstantiated())));
3643}
3644
3645TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3646 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3647 "class Y { A<int> a; }; Y y;",
3648 declStmt(isInTemplateInstantiation())));
3649}
3650
3651TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3652 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3653 declStmt(isInTemplateInstantiation())));
3654}
3655
3656TEST(IsInstantiated, MatchesFunctionInstantiation) {
3657 EXPECT_TRUE(
3658 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3659 functionDecl(isInstantiated())));
3660}
3661
3662TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3663 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3664 varDecl(isInstantiated())));
3665}
3666
3667TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3668 EXPECT_TRUE(
3669 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3670 declStmt(isInTemplateInstantiation())));
3671}
3672
3673TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3674 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3675 declStmt(isInTemplateInstantiation())));
3676}
3677
3678TEST(IsInTemplateInstantiation, Sharing) {
3679 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3680 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3681 // and makes the matcher behave in non-obvious ways.
3682 EXPECT_TRUE(notMatches(
3683 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3684 Matcher));
3685 EXPECT_TRUE(matches(
3686 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3687 Matcher));
3688}
3689
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003690TEST(IsExplicitTemplateSpecialization,
3691 DoesNotMatchPrimaryTemplate) {
3692 EXPECT_TRUE(notMatches(
3693 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003694 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003695 EXPECT_TRUE(notMatches(
3696 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003697 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003698}
3699
3700TEST(IsExplicitTemplateSpecialization,
3701 DoesNotMatchExplicitTemplateInstantiations) {
3702 EXPECT_TRUE(notMatches(
3703 "template <typename T> class X {};"
3704 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003705 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003706 EXPECT_TRUE(notMatches(
3707 "template <typename T> void f(T t) {}"
3708 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003709 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003710}
3711
3712TEST(IsExplicitTemplateSpecialization,
3713 DoesNotMatchImplicitTemplateInstantiations) {
3714 EXPECT_TRUE(notMatches(
3715 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003716 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003717 EXPECT_TRUE(notMatches(
3718 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003719 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003720}
3721
3722TEST(IsExplicitTemplateSpecialization,
3723 MatchesExplicitTemplateSpecializations) {
3724 EXPECT_TRUE(matches(
3725 "template <typename T> class X {};"
3726 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003727 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003728 EXPECT_TRUE(matches(
3729 "template <typename T> void f(T t) {}"
3730 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003731 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003732}
3733
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003734TEST(HasAncenstor, MatchesDeclarationAncestors) {
3735 EXPECT_TRUE(matches(
3736 "class A { class B { class C {}; }; };",
3737 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3738}
3739
3740TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3741 EXPECT_TRUE(notMatches(
3742 "class A { class B { class C {}; }; };",
3743 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3744}
3745
3746TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3747 EXPECT_TRUE(matches(
3748 "class A { class B { void f() { C c; } class C {}; }; };",
3749 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3750 hasAncestor(recordDecl(hasName("A"))))))));
3751}
3752
3753TEST(HasAncenstor, MatchesStatementAncestors) {
3754 EXPECT_TRUE(matches(
3755 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003756 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003757}
3758
3759TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3760 EXPECT_TRUE(matches(
3761 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003762 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003763}
3764
3765TEST(HasAncestor, BindsRecursiveCombinations) {
3766 EXPECT_TRUE(matchAndVerifyResultTrue(
3767 "class C { class D { class E { class F { int y; }; }; }; };",
3768 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003769 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003770}
3771
3772TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3773 EXPECT_TRUE(matchAndVerifyResultTrue(
3774 "class C { class D { class E { class F { int y; }; }; }; };",
3775 fieldDecl(hasAncestor(
3776 decl(
3777 hasDescendant(recordDecl(isDefinition(),
3778 hasAncestor(recordDecl())))
3779 ).bind("d")
3780 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003781 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003782}
3783
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003784TEST(HasAncestor, MatchesClosestAncestor) {
3785 EXPECT_TRUE(matchAndVerifyResultTrue(
3786 "template <typename T> struct C {"
3787 " void f(int) {"
3788 " struct I { void g(T) { int x; } } i; i.g(42);"
3789 " }"
3790 "};"
3791 "template struct C<int>;",
3792 varDecl(hasName("x"),
3793 hasAncestor(functionDecl(hasParameter(
3794 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3795 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3796}
3797
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003798TEST(HasAncestor, MatchesInTemplateInstantiations) {
3799 EXPECT_TRUE(matches(
3800 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3801 "A<int>::B::C a;",
3802 fieldDecl(hasType(asString("int")),
3803 hasAncestor(recordDecl(hasName("A"))))));
3804}
3805
3806TEST(HasAncestor, MatchesInImplicitCode) {
3807 EXPECT_TRUE(matches(
3808 "struct X {}; struct A { A() {} X x; };",
3809 constructorDecl(
3810 hasAnyConstructorInitializer(withInitializer(expr(
3811 hasAncestor(recordDecl(hasName("A")))))))));
3812}
3813
Daniel Jasper632aea92012-10-22 16:26:51 +00003814TEST(HasParent, MatchesOnlyParent) {
3815 EXPECT_TRUE(matches(
3816 "void f() { if (true) { int x = 42; } }",
3817 compoundStmt(hasParent(ifStmt()))));
3818 EXPECT_TRUE(notMatches(
3819 "void f() { for (;;) { int x = 42; } }",
3820 compoundStmt(hasParent(ifStmt()))));
3821 EXPECT_TRUE(notMatches(
3822 "void f() { if (true) for (;;) { int x = 42; } }",
3823 compoundStmt(hasParent(ifStmt()))));
3824}
3825
Manuel Klimekc844a462012-12-06 14:42:48 +00003826TEST(HasAncestor, MatchesAllAncestors) {
3827 EXPECT_TRUE(matches(
3828 "template <typename T> struct C { static void f() { 42; } };"
3829 "void t() { C<int>::f(); }",
3830 integerLiteral(
3831 equals(42),
3832 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3833 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3834}
3835
3836TEST(HasParent, MatchesAllParents) {
3837 EXPECT_TRUE(matches(
3838 "template <typename T> struct C { static void f() { 42; } };"
3839 "void t() { C<int>::f(); }",
3840 integerLiteral(
3841 equals(42),
3842 hasParent(compoundStmt(hasParent(functionDecl(
3843 hasParent(recordDecl(isTemplateInstantiation())))))))));
3844 EXPECT_TRUE(matches(
3845 "template <typename T> struct C { static void f() { 42; } };"
3846 "void t() { C<int>::f(); }",
3847 integerLiteral(
3848 equals(42),
3849 hasParent(compoundStmt(hasParent(functionDecl(
3850 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3851 EXPECT_TRUE(matches(
3852 "template <typename T> struct C { static void f() { 42; } };"
3853 "void t() { C<int>::f(); }",
3854 integerLiteral(equals(42),
3855 hasParent(compoundStmt(allOf(
3856 hasParent(functionDecl(
3857 hasParent(recordDecl(isTemplateInstantiation())))),
3858 hasParent(functionDecl(hasParent(recordDecl(
3859 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003860 EXPECT_TRUE(
3861 notMatches("template <typename T> struct C { static void f() {} };"
3862 "void t() { C<int>::f(); }",
3863 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003864}
3865
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003866TEST(HasParent, NoDuplicateParents) {
3867 class HasDuplicateParents : public BoundNodesCallback {
3868 public:
3869 bool run(const BoundNodes *Nodes) override { return false; }
3870 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3871 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3872 std::set<const void *> Parents;
3873 for (const auto &Parent : Context->getParents(*Node)) {
3874 if (!Parents.insert(Parent.getMemoizationData()).second) {
3875 return true;
3876 }
3877 }
3878 return false;
3879 }
3880 };
3881 EXPECT_FALSE(matchAndVerifyResultTrue(
3882 "template <typename T> int Foo() { return 1 + 2; }\n"
3883 "int x = Foo<int>() + Foo<unsigned>();",
3884 stmt().bind("node"), new HasDuplicateParents()));
3885}
3886
Daniel Jasper516b02e2012-10-17 08:52:59 +00003887TEST(TypeMatching, MatchesTypes) {
3888 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3889}
3890
Samuel Benzaquenb405c082014-12-15 15:09:22 +00003891TEST(TypeMatching, MatchesVoid) {
3892 EXPECT_TRUE(
3893 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
3894}
3895
Daniel Jasper516b02e2012-10-17 08:52:59 +00003896TEST(TypeMatching, MatchesArrayTypes) {
3897 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3898 EXPECT_TRUE(matches("int a[42];", arrayType()));
3899 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3900
3901 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3902 arrayType(hasElementType(builtinType()))));
3903
3904 EXPECT_TRUE(matches(
3905 "int const a[] = { 2, 3 };",
3906 qualType(arrayType(hasElementType(builtinType())))));
3907 EXPECT_TRUE(matches(
3908 "int const a[] = { 2, 3 };",
3909 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3910 EXPECT_TRUE(matches(
3911 "typedef const int T; T x[] = { 1, 2 };",
3912 qualType(isConstQualified(), arrayType())));
3913
3914 EXPECT_TRUE(notMatches(
3915 "int a[] = { 2, 3 };",
3916 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3917 EXPECT_TRUE(notMatches(
3918 "int a[] = { 2, 3 };",
3919 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3920 EXPECT_TRUE(notMatches(
3921 "int const a[] = { 2, 3 };",
3922 qualType(arrayType(hasElementType(builtinType())),
3923 unless(isConstQualified()))));
3924
3925 EXPECT_TRUE(matches("int a[2];",
3926 constantArrayType(hasElementType(builtinType()))));
3927 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3928}
3929
3930TEST(TypeMatching, MatchesComplexTypes) {
3931 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3932 EXPECT_TRUE(matches(
3933 "_Complex float f;",
3934 complexType(hasElementType(builtinType()))));
3935 EXPECT_TRUE(notMatches(
3936 "_Complex float f;",
3937 complexType(hasElementType(isInteger()))));
3938}
3939
3940TEST(TypeMatching, MatchesConstantArrayTypes) {
3941 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3942 EXPECT_TRUE(notMatches(
3943 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3944 constantArrayType(hasElementType(builtinType()))));
3945
3946 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3947 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3948 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3949}
3950
3951TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3952 EXPECT_TRUE(matches(
3953 "template <typename T, int Size> class array { T data[Size]; };",
3954 dependentSizedArrayType()));
3955 EXPECT_TRUE(notMatches(
3956 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3957 dependentSizedArrayType()));
3958}
3959
3960TEST(TypeMatching, MatchesIncompleteArrayType) {
3961 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3962 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3963
3964 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3965 incompleteArrayType()));
3966}
3967
3968TEST(TypeMatching, MatchesVariableArrayType) {
3969 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3970 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3971
3972 EXPECT_TRUE(matches(
3973 "void f(int b) { int a[b]; }",
3974 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3975 varDecl(hasName("b")))))))));
3976}
3977
3978TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003979 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3980 llvm::Triple::Win32) {
3981 // FIXME: Make this work for MSVC.
3982 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003983
David Majnemer197e2102014-03-05 06:32:38 +00003984 EXPECT_TRUE(matches("_Atomic(int) i;",
3985 atomicType(hasValueType(isInteger()))));
3986 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3987 atomicType(hasValueType(isInteger()))));
3988 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003989}
3990
3991TEST(TypeMatching, MatchesAutoTypes) {
3992 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3993 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3994 autoType()));
3995
Richard Smith061f1e22013-04-30 21:23:01 +00003996 // FIXME: Matching against the type-as-written can't work here, because the
3997 // type as written was not deduced.
3998 //EXPECT_TRUE(matches("auto a = 1;",
3999 // autoType(hasDeducedType(isInteger()))));
4000 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4001 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004002}
4003
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004004TEST(TypeMatching, MatchesFunctionTypes) {
4005 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4006 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4007}
4008
Edwin Vaneec074802013-04-01 18:33:34 +00004009TEST(TypeMatching, MatchesParenType) {
4010 EXPECT_TRUE(
4011 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4012 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4013
4014 EXPECT_TRUE(matches(
4015 "int (*ptr_to_func)(int);",
4016 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4017 EXPECT_TRUE(notMatches(
4018 "int (*ptr_to_array)[4];",
4019 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4020}
4021
Daniel Jasper516b02e2012-10-17 08:52:59 +00004022TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004023 // FIXME: Reactive when these tests can be more specific (not matching
4024 // implicit code on certain platforms), likely when we have hasDescendant for
4025 // Types/TypeLocs.
4026 //EXPECT_TRUE(matchAndVerifyResultTrue(
4027 // "int* a;",
4028 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4029 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4030 //EXPECT_TRUE(matchAndVerifyResultTrue(
4031 // "int* a;",
4032 // pointerTypeLoc().bind("loc"),
4033 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004034 EXPECT_TRUE(matches(
4035 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004036 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004037 EXPECT_TRUE(matches(
4038 "int** a;",
4039 loc(pointerType(pointee(pointerType())))));
4040 EXPECT_TRUE(matches(
4041 "int* b; int* * const a = &b;",
4042 loc(qualType(isConstQualified(), pointerType()))));
4043
4044 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004045 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4046 hasType(blockPointerType()))));
4047 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4048 hasType(memberPointerType()))));
4049 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4050 hasType(pointerType()))));
4051 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4052 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004053 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4054 hasType(lValueReferenceType()))));
4055 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4056 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004057
Daniel Jasper7943eb52012-10-17 13:35:36 +00004058 Fragment = "int *ptr;";
4059 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4060 hasType(blockPointerType()))));
4061 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4062 hasType(memberPointerType()))));
4063 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4064 hasType(pointerType()))));
4065 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4066 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004067
Daniel Jasper7943eb52012-10-17 13:35:36 +00004068 Fragment = "int a; int &ref = a;";
4069 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4070 hasType(blockPointerType()))));
4071 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4072 hasType(memberPointerType()))));
4073 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4074 hasType(pointerType()))));
4075 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4076 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004077 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4078 hasType(lValueReferenceType()))));
4079 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4080 hasType(rValueReferenceType()))));
4081
4082 Fragment = "int &&ref = 2;";
4083 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4084 hasType(blockPointerType()))));
4085 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4086 hasType(memberPointerType()))));
4087 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4088 hasType(pointerType()))));
4089 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4090 hasType(referenceType()))));
4091 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4092 hasType(lValueReferenceType()))));
4093 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4094 hasType(rValueReferenceType()))));
4095}
4096
4097TEST(TypeMatching, AutoRefTypes) {
4098 std::string Fragment = "auto a = 1;"
4099 "auto b = a;"
4100 "auto &c = a;"
4101 "auto &&d = c;"
4102 "auto &&e = 2;";
4103 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4104 hasType(referenceType()))));
4105 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4106 hasType(referenceType()))));
4107 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4108 hasType(referenceType()))));
4109 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4110 hasType(lValueReferenceType()))));
4111 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4112 hasType(rValueReferenceType()))));
4113 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4114 hasType(referenceType()))));
4115 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4116 hasType(lValueReferenceType()))));
4117 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4118 hasType(rValueReferenceType()))));
4119 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4120 hasType(referenceType()))));
4121 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4122 hasType(lValueReferenceType()))));
4123 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4124 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004125}
4126
4127TEST(TypeMatching, PointeeTypes) {
4128 EXPECT_TRUE(matches("int b; int &a = b;",
4129 referenceType(pointee(builtinType()))));
4130 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4131
4132 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004133 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004134
4135 EXPECT_TRUE(matches(
4136 "int const *A;",
4137 pointerType(pointee(isConstQualified(), builtinType()))));
4138 EXPECT_TRUE(notMatches(
4139 "int *A;",
4140 pointerType(pointee(isConstQualified(), builtinType()))));
4141}
4142
4143TEST(TypeMatching, MatchesPointersToConstTypes) {
4144 EXPECT_TRUE(matches("int b; int * const a = &b;",
4145 loc(pointerType())));
4146 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004147 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004148 EXPECT_TRUE(matches(
4149 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004150 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004151 EXPECT_TRUE(matches(
4152 "int b; const int * a = &b;",
4153 pointerType(pointee(builtinType()))));
4154}
4155
4156TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004157 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4158 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004159}
4160
Edwin Vanef901b712013-02-25 14:49:29 +00004161TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004162 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004163 templateSpecializationType()));
4164}
4165
Edwin Vaneb6eae142013-02-25 20:43:32 +00004166TEST(TypeMatching, MatchesRecordType) {
4167 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004168 EXPECT_TRUE(matches("struct S{}; S s;",
4169 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4170 EXPECT_TRUE(notMatches("int i;",
4171 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004172}
4173
4174TEST(TypeMatching, MatchesElaboratedType) {
4175 EXPECT_TRUE(matches(
4176 "namespace N {"
4177 " namespace M {"
4178 " class D {};"
4179 " }"
4180 "}"
4181 "N::M::D d;", elaboratedType()));
4182 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4183 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4184}
4185
4186TEST(ElaboratedTypeNarrowing, hasQualifier) {
4187 EXPECT_TRUE(matches(
4188 "namespace N {"
4189 " namespace M {"
4190 " class D {};"
4191 " }"
4192 "}"
4193 "N::M::D d;",
4194 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4195 EXPECT_TRUE(notMatches(
4196 "namespace M {"
4197 " class D {};"
4198 "}"
4199 "M::D d;",
4200 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004201 EXPECT_TRUE(notMatches(
4202 "struct D {"
4203 "} d;",
4204 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004205}
4206
4207TEST(ElaboratedTypeNarrowing, namesType) {
4208 EXPECT_TRUE(matches(
4209 "namespace N {"
4210 " namespace M {"
4211 " class D {};"
4212 " }"
4213 "}"
4214 "N::M::D d;",
4215 elaboratedType(elaboratedType(namesType(recordType(
4216 hasDeclaration(namedDecl(hasName("D")))))))));
4217 EXPECT_TRUE(notMatches(
4218 "namespace M {"
4219 " class D {};"
4220 "}"
4221 "M::D d;",
4222 elaboratedType(elaboratedType(namesType(typedefType())))));
4223}
4224
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004225TEST(NNS, MatchesNestedNameSpecifiers) {
4226 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4227 nestedNameSpecifier()));
4228 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4229 nestedNameSpecifier()));
4230 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4231 nestedNameSpecifier()));
4232
4233 EXPECT_TRUE(matches(
4234 "struct A { static void f() {} }; void g() { A::f(); }",
4235 nestedNameSpecifier()));
4236 EXPECT_TRUE(notMatches(
4237 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4238 nestedNameSpecifier()));
4239}
4240
Daniel Jasper87c3d362012-09-20 14:12:57 +00004241TEST(NullStatement, SimpleCases) {
4242 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4243 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4244}
4245
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004246TEST(NNS, MatchesTypes) {
4247 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4248 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4249 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4250 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4251 Matcher));
4252 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4253}
4254
4255TEST(NNS, MatchesNamespaceDecls) {
4256 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4257 specifiesNamespace(hasName("ns")));
4258 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4259 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4260 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4261}
4262
4263TEST(NNS, BindsNestedNameSpecifiers) {
4264 EXPECT_TRUE(matchAndVerifyResultTrue(
4265 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4266 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4267 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4268}
4269
4270TEST(NNS, BindsNestedNameSpecifierLocs) {
4271 EXPECT_TRUE(matchAndVerifyResultTrue(
4272 "namespace ns { struct B {}; } ns::B b;",
4273 loc(nestedNameSpecifier()).bind("loc"),
4274 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4275}
4276
4277TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4278 EXPECT_TRUE(matches(
4279 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4280 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4281 EXPECT_TRUE(matches(
4282 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004283 nestedNameSpecifierLoc(hasPrefix(
4284 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004285}
4286
Daniel Jasper6fc34332012-10-30 15:42:00 +00004287TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4288 std::string Fragment =
4289 "namespace a { struct A { struct B { struct C {}; }; }; };"
4290 "void f() { a::A::B::C c; }";
4291 EXPECT_TRUE(matches(
4292 Fragment,
4293 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4294 hasDescendant(nestedNameSpecifier(
4295 specifiesNamespace(hasName("a")))))));
4296 EXPECT_TRUE(notMatches(
4297 Fragment,
4298 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4299 has(nestedNameSpecifier(
4300 specifiesNamespace(hasName("a")))))));
4301 EXPECT_TRUE(matches(
4302 Fragment,
4303 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4304 has(nestedNameSpecifier(
4305 specifiesNamespace(hasName("a")))))));
4306
4307 // Not really useful because a NestedNameSpecifier can af at most one child,
4308 // but to complete the interface.
4309 EXPECT_TRUE(matchAndVerifyResultTrue(
4310 Fragment,
4311 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4312 forEach(nestedNameSpecifier().bind("x"))),
4313 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4314}
4315
4316TEST(NNS, NestedNameSpecifiersAsDescendants) {
4317 std::string Fragment =
4318 "namespace a { struct A { struct B { struct C {}; }; }; };"
4319 "void f() { a::A::B::C c; }";
4320 EXPECT_TRUE(matches(
4321 Fragment,
4322 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4323 asString("struct a::A")))))));
4324 EXPECT_TRUE(matchAndVerifyResultTrue(
4325 Fragment,
4326 functionDecl(hasName("f"),
4327 forEachDescendant(nestedNameSpecifier().bind("x"))),
4328 // Nested names: a, a::A and a::A::B.
4329 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4330}
4331
4332TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4333 std::string Fragment =
4334 "namespace a { struct A { struct B { struct C {}; }; }; };"
4335 "void f() { a::A::B::C c; }";
4336 EXPECT_TRUE(matches(
4337 Fragment,
4338 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4339 hasDescendant(loc(nestedNameSpecifier(
4340 specifiesNamespace(hasName("a"))))))));
4341 EXPECT_TRUE(notMatches(
4342 Fragment,
4343 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4344 has(loc(nestedNameSpecifier(
4345 specifiesNamespace(hasName("a"))))))));
4346 EXPECT_TRUE(matches(
4347 Fragment,
4348 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4349 has(loc(nestedNameSpecifier(
4350 specifiesNamespace(hasName("a"))))))));
4351
4352 EXPECT_TRUE(matchAndVerifyResultTrue(
4353 Fragment,
4354 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4355 forEach(nestedNameSpecifierLoc().bind("x"))),
4356 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4357}
4358
4359TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4360 std::string Fragment =
4361 "namespace a { struct A { struct B { struct C {}; }; }; };"
4362 "void f() { a::A::B::C c; }";
4363 EXPECT_TRUE(matches(
4364 Fragment,
4365 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4366 asString("struct a::A"))))))));
4367 EXPECT_TRUE(matchAndVerifyResultTrue(
4368 Fragment,
4369 functionDecl(hasName("f"),
4370 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4371 // Nested names: a, a::A and a::A::B.
4372 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4373}
4374
Manuel Klimek191c0932013-02-01 13:41:35 +00004375template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004376public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004377 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4378 StringRef InnerId)
4379 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004380 }
4381
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004382 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004383
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004384 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004385 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004386 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4387 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004388 }
4389private:
4390 std::string Id;
4391 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004392 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004393};
4394
4395TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004396 EXPECT_TRUE(matchAndVerifyResultTrue(
4397 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4398 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004399 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4400 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004401 EXPECT_TRUE(matchAndVerifyResultFalse(
4402 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4403 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004404 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4405 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004406}
4407
4408TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004409 EXPECT_TRUE(matchAndVerifyResultTrue(
4410 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004411 new VerifyMatchOnNode<clang::Stmt>(
4412 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004413 EXPECT_TRUE(matchAndVerifyResultFalse(
4414 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004415 new VerifyMatchOnNode<clang::Stmt>(
4416 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004417}
4418
4419TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4420 EXPECT_TRUE(matchAndVerifyResultTrue(
4421 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4422 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004423 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004424 EXPECT_TRUE(matchAndVerifyResultFalse(
4425 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4426 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004427 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004428}
4429
Manuel Klimekbee08572013-02-07 12:42:10 +00004430template <typename T>
4431class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4432public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004433 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004434
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004435 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004436 const T *Node = Nodes->getNodeAs<T>("");
4437 return verify(*Nodes, *Context, Node);
4438 }
4439
4440 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004441 // Use the original typed pointer to verify we can pass pointers to subtypes
4442 // to equalsNode.
4443 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004444 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004445 "", match(stmt(hasParent(
4446 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004447 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004448 }
4449 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004450 // Use the original typed pointer to verify we can pass pointers to subtypes
4451 // to equalsNode.
4452 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004453 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004454 "", match(decl(hasParent(
4455 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004456 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004457 }
4458};
4459
4460TEST(IsEqualTo, MatchesNodesByIdentity) {
4461 EXPECT_TRUE(matchAndVerifyResultTrue(
4462 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004463 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4464 EXPECT_TRUE(matchAndVerifyResultTrue(
4465 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4466 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004467}
4468
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004469TEST(MatchFinder, CheckProfiling) {
4470 MatchFinder::MatchFinderOptions Options;
4471 llvm::StringMap<llvm::TimeRecord> Records;
4472 Options.CheckProfiling.emplace(Records);
4473 MatchFinder Finder(std::move(Options));
4474
4475 struct NamedCallback : public MatchFinder::MatchCallback {
4476 void run(const MatchFinder::MatchResult &Result) override {}
4477 StringRef getID() const override { return "MyID"; }
4478 } Callback;
4479 Finder.addMatcher(decl(), &Callback);
4480 std::unique_ptr<FrontendActionFactory> Factory(
4481 newFrontendActionFactory(&Finder));
4482 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4483
4484 EXPECT_EQ(1u, Records.size());
4485 EXPECT_EQ("MyID", Records.begin()->getKey());
4486}
4487
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004488class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4489public:
4490 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004491 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004492 EXPECT_TRUE(Called);
4493 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004494 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004495 bool Called;
4496};
4497
4498TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4499 MatchFinder Finder;
4500 VerifyStartOfTranslationUnit VerifyCallback;
4501 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004502 std::unique_ptr<FrontendActionFactory> Factory(
4503 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004504 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4505 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004506
4507 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004508 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004509 ASSERT_TRUE(AST.get());
4510 Finder.matchAST(AST->getASTContext());
4511 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004512}
4513
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004514class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4515public:
4516 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004517 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004518 EXPECT_FALSE(Called);
4519 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004520 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004521 bool Called;
4522};
4523
4524TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4525 MatchFinder Finder;
4526 VerifyEndOfTranslationUnit VerifyCallback;
4527 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004528 std::unique_ptr<FrontendActionFactory> Factory(
4529 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004530 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4531 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004532
4533 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004534 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004535 ASSERT_TRUE(AST.get());
4536 Finder.matchAST(AST->getASTContext());
4537 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004538}
4539
Manuel Klimekbbb75852013-06-20 14:06:32 +00004540TEST(EqualsBoundNodeMatcher, QualType) {
4541 EXPECT_TRUE(matches(
4542 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4543 hasInitializer(ignoringParenImpCasts(
4544 hasType(qualType(equalsBoundNode("type"))))))));
4545 EXPECT_TRUE(notMatches("int i = 1.f;",
4546 varDecl(hasType(qualType().bind("type")),
4547 hasInitializer(ignoringParenImpCasts(hasType(
4548 qualType(equalsBoundNode("type"))))))));
4549}
4550
4551TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4552 EXPECT_TRUE(notMatches(
4553 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4554 hasInitializer(ignoringParenImpCasts(
4555 hasType(qualType(equalsBoundNode("type"))))))));
4556}
4557
4558TEST(EqualsBoundNodeMatcher, Stmt) {
4559 EXPECT_TRUE(
4560 matches("void f() { if(true) {} }",
4561 stmt(allOf(ifStmt().bind("if"),
4562 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4563
4564 EXPECT_TRUE(notMatches(
4565 "void f() { if(true) { if (true) {} } }",
4566 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4567}
4568
4569TEST(EqualsBoundNodeMatcher, Decl) {
4570 EXPECT_TRUE(matches(
4571 "class X { class Y {}; };",
4572 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4573 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4574
4575 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4576 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4577 has(decl(equalsBoundNode("record")))))));
4578}
4579
4580TEST(EqualsBoundNodeMatcher, Type) {
4581 EXPECT_TRUE(matches(
4582 "class X { int a; int b; };",
4583 recordDecl(
4584 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4585 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4586
4587 EXPECT_TRUE(notMatches(
4588 "class X { int a; double b; };",
4589 recordDecl(
4590 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4591 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4592}
4593
4594TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004595 EXPECT_TRUE(matchAndVerifyResultTrue(
4596 "int f() {"
4597 " if (1) {"
4598 " int i = 9;"
4599 " }"
4600 " int j = 10;"
4601 " {"
4602 " float k = 9.0;"
4603 " }"
4604 " return 0;"
4605 "}",
4606 // Look for variable declarations within functions whose type is the same
4607 // as the function return type.
4608 functionDecl(returns(qualType().bind("type")),
4609 forEachDescendant(varDecl(hasType(
4610 qualType(equalsBoundNode("type")))).bind("decl"))),
4611 // Only i and j should match, not k.
4612 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4613}
4614
4615TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4616 EXPECT_TRUE(matchAndVerifyResultTrue(
4617 "void f() {"
4618 " int x;"
4619 " double d;"
4620 " x = d + x - d + x;"
4621 "}",
4622 functionDecl(
4623 hasName("f"), forEachDescendant(varDecl().bind("d")),
4624 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4625 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4626}
4627
Manuel Klimekce68f772014-03-25 14:39:26 +00004628TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4629 EXPECT_TRUE(matchAndVerifyResultTrue(
4630 "struct StringRef { int size() const; const char* data() const; };"
4631 "void f(StringRef v) {"
4632 " v.data();"
4633 "}",
4634 memberCallExpr(
4635 callee(methodDecl(hasName("data"))),
4636 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4637 .bind("var")))),
4638 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4639 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4640 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4641 .bind("data"),
4642 new VerifyIdIsBoundTo<Expr>("data", 1)));
4643
4644 EXPECT_FALSE(matches(
4645 "struct StringRef { int size() const; const char* data() const; };"
4646 "void f(StringRef v) {"
4647 " v.data();"
4648 " v.size();"
4649 "}",
4650 memberCallExpr(
4651 callee(methodDecl(hasName("data"))),
4652 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4653 .bind("var")))),
4654 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4655 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4656 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4657 .bind("data")));
4658}
4659
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004660TEST(TypeDefDeclMatcher, Match) {
4661 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4662 typedefDecl(hasName("typedefDeclTest"))));
4663}
4664
4665// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4666#ifndef LLVM_ON_WIN32
4667
4668TEST(Matcher, IsExpansionInMainFileMatcher) {
4669 EXPECT_TRUE(matches("class X {};",
4670 recordDecl(hasName("X"), isExpansionInMainFile())));
4671 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4672 FileContentMappings M;
4673 M.push_back(std::make_pair("/other", "class X {};"));
4674 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4675 recordDecl(isExpansionInMainFile()), false,
4676 "-isystem/", M));
4677}
4678
4679TEST(Matcher, IsExpansionInSystemHeader) {
4680 FileContentMappings M;
4681 M.push_back(std::make_pair("/other", "class X {};"));
4682 EXPECT_TRUE(matchesConditionally(
4683 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4684 "-isystem/", M));
4685 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4686 recordDecl(isExpansionInSystemHeader()),
4687 false, "-I/", M));
4688 EXPECT_TRUE(notMatches("class X {};",
4689 recordDecl(isExpansionInSystemHeader())));
4690 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4691}
4692
4693TEST(Matcher, IsExpansionInFileMatching) {
4694 FileContentMappings M;
4695 M.push_back(std::make_pair("/foo", "class A {};"));
4696 M.push_back(std::make_pair("/bar", "class B {};"));
4697 EXPECT_TRUE(matchesConditionally(
4698 "#include <foo>\n"
4699 "#include <bar>\n"
4700 "class X {};",
4701 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4702 "-isystem/", M));
4703 EXPECT_TRUE(matchesConditionally(
4704 "#include <foo>\n"
4705 "#include <bar>\n"
4706 "class X {};",
4707 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4708 "-isystem/", M));
4709}
4710
4711#endif // LLVM_ON_WIN32
4712
Manuel Klimekbfa43572015-03-12 15:48:15 +00004713
4714TEST(ObjCMessageExprMatcher, SimpleExprs) {
4715 // don't find ObjCMessageExpr where none are present
4716 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
4717
4718 std::string Objc1String =
4719 "@interface Str "
4720 " - (Str *)uppercaseString:(Str *)str;"
4721 "@end "
4722 "@interface foo "
4723 "- (void)meth:(Str *)text;"
4724 "@end "
4725 " "
4726 "@implementation foo "
4727 "- (void) meth:(Str *)text { "
4728 " [self contents];"
4729 " Str *up = [text uppercaseString];"
4730 "} "
4731 "@end ";
4732 EXPECT_TRUE(matchesObjC(
4733 Objc1String,
4734 objcMessageExpr(anything())));
4735 EXPECT_TRUE(matchesObjC(
4736 Objc1String,
4737 objcMessageExpr(hasSelector("contents"))));
4738 EXPECT_TRUE(matchesObjC(
4739 Objc1String,
4740 objcMessageExpr(matchesSelector("cont*"))));
4741 EXPECT_FALSE(matchesObjC(
4742 Objc1String,
4743 objcMessageExpr(matchesSelector("?cont*"))));
4744 EXPECT_TRUE(notMatchesObjC(
4745 Objc1String,
4746 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
4747 EXPECT_TRUE(matchesObjC(
4748 Objc1String,
4749 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
4750 EXPECT_TRUE(matchesObjC(
4751 Objc1String,
4752 objcMessageExpr(matchesSelector("uppercase*"),
4753 argumentCountIs(0)
4754 )));
4755
4756}
4757
Manuel Klimek04616e42012-07-06 05:48:52 +00004758} // end namespace ast_matchers
4759} // end namespace clang