blob: b4435583d530ca45077c6fc976d67b8081b5e719 [file] [log] [blame]
Manuel Klimek04616e42012-07-06 05:48:52 +00001//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher unit tests ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ASTMatchersTest.h"
Benjamin Kramere5015e52012-12-01 17:22:05 +000011#include "clang/AST/PrettyPrinter.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Chandler Carruth320d9662012-12-04 09:45:34 +000013#include "clang/ASTMatchers/ASTMatchers.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000014#include "clang/Tooling/Tooling.h"
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +000015#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000017#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000022#if GTEST_HAS_DEATH_TEST
Manuel Klimek04616e42012-07-06 05:48:52 +000023TEST(HasNameDeathTest, DiesOnEmptyName) {
24 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000025 DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000026 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27 }, "");
28}
29
Daniel Jasper1dad1832012-07-10 20:20:19 +000030TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000032 DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
Daniel Jasper1dad1832012-07-10 20:20:19 +000033 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34 }, "");
35}
36
Manuel Klimek04616e42012-07-06 05:48:52 +000037TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000039 DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000040 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41 }, "");
42}
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000043#endif
Manuel Klimek04616e42012-07-06 05:48:52 +000044
Peter Collingbourne2b9471302013-11-07 22:30:32 +000045TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46 MatchFinder Finder;
Craig Topper416fa342014-06-08 08:38:12 +000047 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50 nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000051
52 // Do not accept non-toplevel matchers.
Craig Topper416fa342014-06-08 08:38:12 +000053 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54 EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000056}
57
Manuel Klimeke9235692012-07-25 10:02:02 +000058TEST(Decl, MatchesDeclarations) {
59 EXPECT_TRUE(notMatches("", decl(usingDecl())));
60 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
61 decl(usingDecl())));
62}
63
Manuel Klimek04616e42012-07-06 05:48:52 +000064TEST(NameableDeclaration, MatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000065 DeclarationMatcher NamedX = namedDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +000066 EXPECT_TRUE(matches("typedef int X;", NamedX));
67 EXPECT_TRUE(matches("int X;", NamedX));
68 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
69 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
70 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
71 EXPECT_TRUE(matches("namespace X { }", NamedX));
Daniel Jasper1dad1832012-07-10 20:20:19 +000072 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
Manuel Klimek04616e42012-07-06 05:48:52 +000073
74 EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
Daniel Jasper1dad1832012-07-10 20:20:19 +000077TEST(NameableDeclaration, REMatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000078 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000079 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
80 EXPECT_TRUE(matches("int Xb;", NamedX));
81 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
82 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
83 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
84 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
85 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
86
87 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
88
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000089 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000090 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
91 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
92
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000093 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000094 EXPECT_TRUE(matches("int abc;", Abc));
95 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
96 EXPECT_TRUE(notMatches("int cab;", Abc));
97 EXPECT_TRUE(matches("int cabc;", Abc));
Manuel Klimeke792efd2012-12-10 07:08:53 +000098
99 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
100 EXPECT_TRUE(matches("int k;", StartsWithK));
101 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
102 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
103 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
104 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000105}
106
Manuel Klimek04616e42012-07-06 05:48:52 +0000107TEST(DeclarationMatcher, MatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000108 DeclarationMatcher ClassMatcher(recordDecl());
Saleem Abdulrasool377066a2014-03-27 22:50:18 +0000109 llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110 if (Triple.getOS() != llvm::Triple::Win32 ||
111 Triple.getEnvironment() != llvm::Triple::MSVC)
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +0000112 EXPECT_FALSE(matches("", ClassMatcher));
113 else
114 // Matches class type_info.
115 EXPECT_TRUE(matches("", ClassMatcher));
Manuel Klimek04616e42012-07-06 05:48:52 +0000116
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000117 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000118 EXPECT_TRUE(matches("class X;", ClassX));
119 EXPECT_TRUE(matches("class X {};", ClassX));
120 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
121 EXPECT_TRUE(notMatches("", ClassX));
122}
123
124TEST(DeclarationMatcher, ClassIsDerived) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000125 DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000126
127 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000128 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
Manuel Klimek04616e42012-07-06 05:48:52 +0000130 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131 EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
Daniel Jasperd6b82cb2012-09-12 21:14:15 +0000133 DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000134
135 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
136 EXPECT_TRUE(matches("class X {};", IsAX));
137 EXPECT_TRUE(matches("class X;", IsAX));
138 EXPECT_TRUE(notMatches("class Y;", IsAX));
139 EXPECT_TRUE(notMatches("", IsAX));
140
Manuel Klimek04616e42012-07-06 05:48:52 +0000141 DeclarationMatcher ZIsDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000142 recordDecl(hasName("Z"), isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000143 EXPECT_TRUE(
144 matches("class X {}; class Y : public X {}; class Z : public Y {};",
145 ZIsDerivedFromX));
146 EXPECT_TRUE(
147 matches("class X {};"
148 "template<class T> class Y : public X {};"
149 "class Z : public Y<int> {};", ZIsDerivedFromX));
150 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
151 ZIsDerivedFromX));
152 EXPECT_TRUE(
153 matches("template<class T> class X {}; "
154 "template<class T> class Z : public X<T> {};",
155 ZIsDerivedFromX));
156 EXPECT_TRUE(
157 matches("template<class T, class U=T> class X {}; "
158 "template<class T> class Z : public X<T> {};",
159 ZIsDerivedFromX));
160 EXPECT_TRUE(
161 notMatches("template<class X> class A { class Z : public X {}; };",
162 ZIsDerivedFromX));
163 EXPECT_TRUE(
164 matches("template<class X> class A { public: class Z : public X {}; }; "
165 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
166 EXPECT_TRUE(
167 matches("template <class T> class X {}; "
168 "template<class Y> class A { class Z : public X<Y> {}; };",
169 ZIsDerivedFromX));
170 EXPECT_TRUE(
171 notMatches("template<template<class T> class X> class A { "
172 " class Z : public X<int> {}; };", ZIsDerivedFromX));
173 EXPECT_TRUE(
174 matches("template<template<class T> class X> class A { "
175 " public: class Z : public X<int> {}; }; "
176 "template<class T> class X {}; void y() { A<X>::Z z; }",
177 ZIsDerivedFromX));
178 EXPECT_TRUE(
179 notMatches("template<class X> class A { class Z : public X::D {}; };",
180 ZIsDerivedFromX));
181 EXPECT_TRUE(
182 matches("template<class X> class A { public: "
183 " class Z : public X::D {}; }; "
184 "class Y { public: class X {}; typedef X D; }; "
185 "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
186 EXPECT_TRUE(
187 matches("class X {}; typedef X Y; class Z : public Y {};",
188 ZIsDerivedFromX));
189 EXPECT_TRUE(
190 matches("template<class T> class Y { typedef typename T::U X; "
191 " class Z : public X {}; };", ZIsDerivedFromX));
192 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
193 ZIsDerivedFromX));
194 EXPECT_TRUE(
195 notMatches("template<class T> class X {}; "
196 "template<class T> class A { class Z : public X<T>::D {}; };",
197 ZIsDerivedFromX));
198 EXPECT_TRUE(
199 matches("template<class T> class X { public: typedef X<T> D; }; "
200 "template<class T> class A { public: "
201 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
202 ZIsDerivedFromX));
203 EXPECT_TRUE(
204 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
205 ZIsDerivedFromX));
206 EXPECT_TRUE(
207 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
208 ZIsDerivedFromX));
209 EXPECT_TRUE(
210 matches("class X {}; class Y : public X {}; "
211 "typedef Y V; typedef V W; class Z : public W {};",
212 ZIsDerivedFromX));
213 EXPECT_TRUE(
214 matches("template<class T, class U> class X {}; "
215 "template<class T> class A { class Z : public X<T, int> {}; };",
216 ZIsDerivedFromX));
217 EXPECT_TRUE(
218 notMatches("template<class X> class D { typedef X A; typedef A B; "
219 " typedef B C; class Z : public C {}; };",
220 ZIsDerivedFromX));
221 EXPECT_TRUE(
222 matches("class X {}; typedef X A; typedef A B; "
223 "class Z : public B {};", ZIsDerivedFromX));
224 EXPECT_TRUE(
225 matches("class X {}; typedef X A; typedef A B; typedef B C; "
226 "class Z : public C {};", ZIsDerivedFromX));
227 EXPECT_TRUE(
228 matches("class U {}; typedef U X; typedef X V; "
229 "class Z : public V {};", ZIsDerivedFromX));
230 EXPECT_TRUE(
231 matches("class Base {}; typedef Base X; "
232 "class Z : public Base {};", ZIsDerivedFromX));
233 EXPECT_TRUE(
234 matches("class Base {}; typedef Base Base2; typedef Base2 X; "
235 "class Z : public Base {};", ZIsDerivedFromX));
236 EXPECT_TRUE(
237 notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
238 "class Z : public Base {};", ZIsDerivedFromX));
239 EXPECT_TRUE(
240 matches("class A {}; typedef A X; typedef A Y; "
241 "class Z : public Y {};", ZIsDerivedFromX));
242 EXPECT_TRUE(
243 notMatches("template <typename T> class Z;"
244 "template <> class Z<void> {};"
245 "template <typename T> class Z : public Z<void> {};",
246 IsDerivedFromX));
247 EXPECT_TRUE(
248 matches("template <typename T> class X;"
249 "template <> class X<void> {};"
250 "template <typename T> class X : public X<void> {};",
251 IsDerivedFromX));
252 EXPECT_TRUE(matches(
253 "class X {};"
254 "template <typename T> class Z;"
255 "template <> class Z<void> {};"
256 "template <typename T> class Z : public Z<void>, public X {};",
257 ZIsDerivedFromX));
Manuel Klimek5472a522012-12-04 13:40:29 +0000258 EXPECT_TRUE(
259 notMatches("template<int> struct X;"
260 "template<int i> struct X : public X<i-1> {};",
261 recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
262 EXPECT_TRUE(matches(
263 "struct A {};"
264 "template<int> struct X;"
265 "template<int i> struct X : public X<i-1> {};"
266 "template<> struct X<0> : public A {};"
267 "struct B : public X<42> {};",
268 recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000269
270 // FIXME: Once we have better matchers for template type matching,
271 // get rid of the Variable(...) matching and match the right template
272 // declarations directly.
273 const char *RecursiveTemplateOneParameter =
274 "class Base1 {}; class Base2 {};"
275 "template <typename T> class Z;"
276 "template <> class Z<void> : public Base1 {};"
277 "template <> class Z<int> : public Base2 {};"
278 "template <> class Z<float> : public Z<void> {};"
279 "template <> class Z<double> : public Z<int> {};"
280 "template <typename T> class Z : public Z<float>, public Z<double> {};"
281 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
282 EXPECT_TRUE(matches(
283 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000284 varDecl(hasName("z_float"),
285 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000286 EXPECT_TRUE(notMatches(
287 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000288 varDecl(hasName("z_float"),
289 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000290 EXPECT_TRUE(matches(
291 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000292 varDecl(hasName("z_char"),
293 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
294 isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000295
296 const char *RecursiveTemplateTwoParameters =
297 "class Base1 {}; class Base2 {};"
298 "template <typename T1, typename T2> class Z;"
299 "template <typename T> class Z<void, T> : public Base1 {};"
300 "template <typename T> class Z<int, T> : public Base2 {};"
301 "template <typename T> class Z<float, T> : public Z<void, T> {};"
302 "template <typename T> class Z<double, T> : public Z<int, T> {};"
303 "template <typename T1, typename T2> class Z : "
304 " public Z<float, T2>, public Z<double, T2> {};"
305 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
306 " Z<char, void> z_char; }";
307 EXPECT_TRUE(matches(
308 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000309 varDecl(hasName("z_float"),
310 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000311 EXPECT_TRUE(notMatches(
312 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000313 varDecl(hasName("z_float"),
314 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000315 EXPECT_TRUE(matches(
316 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000317 varDecl(hasName("z_char"),
318 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
319 isDerivedFrom("Base2")))))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000322 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000325 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000329 recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
Manuel Klimek1863e502013-08-02 21:24:09 +0000330
331 EXPECT_TRUE(matches(
332 "template<typename T> class X {};"
333 "template<typename T> using Z = X<T>;"
334 "template <typename T> class Y : Z<T> {};",
335 recordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000336}
337
Edwin Vane0a4836e2013-03-06 17:02:57 +0000338TEST(DeclarationMatcher, hasMethod) {
339 EXPECT_TRUE(matches("class A { void func(); };",
340 recordDecl(hasMethod(hasName("func")))));
341 EXPECT_TRUE(notMatches("class A { void func(); };",
342 recordDecl(hasMethod(isPublic()))));
343}
344
Daniel Jasper83dafaf2012-09-18 14:17:42 +0000345TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
346 EXPECT_TRUE(matches(
347 "template <typename T> struct A {"
348 " template <typename T2> struct F {};"
349 "};"
350 "template <typename T> struct B : A<T>::template F<T> {};"
351 "B<int> b;",
352 recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
353}
354
Edwin Vaneb6eae142013-02-25 20:43:32 +0000355TEST(DeclarationMatcher, hasDeclContext) {
356 EXPECT_TRUE(matches(
357 "namespace N {"
358 " namespace M {"
359 " class D {};"
360 " }"
361 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000362 recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000363 EXPECT_TRUE(notMatches(
364 "namespace N {"
365 " namespace M {"
366 " class D {};"
367 " }"
368 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000369 recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
370
371 EXPECT_TRUE(matches("namespace {"
372 " namespace M {"
373 " class D {};"
374 " }"
375 "}",
376 recordDecl(hasDeclContext(namespaceDecl(
377 hasName("M"), hasDeclContext(namespaceDecl()))))));
Samuel Benzaquend93fcc12014-10-27 20:58:44 +0000378
379 EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000380}
381
Samuel Benzaquenef621f42015-02-10 14:46:45 +0000382TEST(DeclarationMatcher, translationUnitDecl) {
383 const std::string Code = "int MyVar1;\n"
384 "namespace NameSpace {\n"
385 "int MyVar2;\n"
386 "} // namespace NameSpace\n";
387 EXPECT_TRUE(matches(
388 Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
389 EXPECT_FALSE(matches(
390 Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
391 EXPECT_TRUE(matches(
392 Code,
393 varDecl(hasName("MyVar2"),
394 hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
395}
396
Manuel Klimek94ad0bf2014-09-04 08:51:06 +0000397TEST(DeclarationMatcher, LinkageSpecification) {
398 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
399 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
400}
401
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000402TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000403 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000404 EXPECT_TRUE(notMatches("class X;", ClassX));
405 EXPECT_TRUE(notMatches("class X {};", ClassX));
406}
407
408TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000409 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000410 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
411 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
412}
413
414TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
415 EXPECT_TRUE(notMatches("template<typename T> class X { };"
416 "template<> class X<int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000417 classTemplateDecl(hasName("X"),
418 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000419}
420
421TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
422 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
423 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000424 classTemplateDecl(hasName("X"),
425 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000426}
427
Daniel Jasper4e566c42012-07-12 08:50:38 +0000428TEST(AllOf, AllOverloadsWork) {
429 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000430 "struct T { };"
431 "int f(int, T*, int, int);"
432 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000433 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000434 callExpr(allOf(callee(functionDecl(hasName("f"))),
435 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000436 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000437 callExpr(allOf(callee(functionDecl(hasName("f"))),
438 hasArgument(0, declRefExpr(to(varDecl()))),
439 hasArgument(1, hasType(pointsTo(
440 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000441 EXPECT_TRUE(matches(Program,
442 callExpr(allOf(callee(functionDecl(hasName("f"))),
443 hasArgument(0, declRefExpr(to(varDecl()))),
444 hasArgument(1, hasType(pointsTo(
445 recordDecl(hasName("T"))))),
446 hasArgument(2, integerLiteral(equals(3)))))));
447 EXPECT_TRUE(matches(Program,
448 callExpr(allOf(callee(functionDecl(hasName("f"))),
449 hasArgument(0, declRefExpr(to(varDecl()))),
450 hasArgument(1, hasType(pointsTo(
451 recordDecl(hasName("T"))))),
452 hasArgument(2, integerLiteral(equals(3))),
453 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000454}
455
Samuel Benzaquenb063f5c2015-07-17 16:05:27 +0000456TEST(ConstructVariadic, MismatchedTypes_Regression) {
457 EXPECT_TRUE(
458 matches("const int a = 0;",
459 internal::DynTypedMatcher::constructVariadic(
460 internal::DynTypedMatcher::VO_AnyOf,
461 ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>(),
462 {isConstQualified(), arrayType()})
463 .convertTo<QualType>()));
464}
465
Manuel Klimek04616e42012-07-06 05:48:52 +0000466TEST(DeclarationMatcher, MatchAnyOf) {
467 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000468 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000469 EXPECT_TRUE(
470 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
471 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
472 EXPECT_TRUE(
473 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
474 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
475
Daniel Jasper84c763e2012-07-15 19:57:12 +0000476 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000477 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000478 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
479 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
480
Manuel Klimek04616e42012-07-06 05:48:52 +0000481 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000482 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
483 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000484 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
485 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
486 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
487 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
488 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
489 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000490
491 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
492 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
493 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
494 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Aaron Ballman8f4699a2015-07-02 14:02:41 +0000495
496 EXPECT_TRUE(
497 matches("void f() try { } catch (int) { } catch (...) { }",
498 catchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000499}
500
501TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000502 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000503 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
504 EXPECT_TRUE(matches("class X {};", HasClassX));
505
506 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000507 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000508 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
509 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
510 EXPECT_TRUE(
511 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
512}
513
514TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
515 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000516 recordDecl(
517 has(recordDecl(
518 has(recordDecl(hasName("X"))),
519 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000520 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000521 has(recordDecl(
522 has(recordDecl(hasName("A"))),
523 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000524 hasName("C"))),
525 hasName("F"));
526
527 EXPECT_TRUE(matches(
528 "class F {"
529 " class Z {"
530 " class X {};"
531 " class Y {};"
532 " };"
533 " class C {"
534 " class A {};"
535 " class B {};"
536 " };"
537 "};", Recursive));
538
539 EXPECT_TRUE(matches(
540 "class F {"
541 " class Z {"
542 " class A {};"
543 " class X {};"
544 " class Y {};"
545 " };"
546 " class C {"
547 " class X {};"
548 " class A {};"
549 " class B {};"
550 " };"
551 "};", Recursive));
552
553 EXPECT_TRUE(matches(
554 "class O1 {"
555 " class O2 {"
556 " class F {"
557 " class Z {"
558 " class A {};"
559 " class X {};"
560 " class Y {};"
561 " };"
562 " class C {"
563 " class X {};"
564 " class A {};"
565 " class B {};"
566 " };"
567 " };"
568 " };"
569 "};", Recursive));
570}
571
572TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
573 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000574 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000575 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000576 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000577 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000578 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000579 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000580 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000581 hasName("Y"))),
582 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000583 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000584 anyOf(
585 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000586 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000587 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000588 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000589 hasName("B")))))),
590 hasName("F")));
591
592 EXPECT_TRUE(matches("class F {};", Recursive));
593 EXPECT_TRUE(matches("class Z {};", Recursive));
594 EXPECT_TRUE(matches("class C {};", Recursive));
595 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
596 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
597 EXPECT_TRUE(
598 matches("class O1 { class O2 {"
599 " class M { class N { class B {}; }; }; "
600 "}; };", Recursive));
601}
602
603TEST(DeclarationMatcher, MatchNot) {
604 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000605 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000606 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000607 unless(hasName("X")));
608 EXPECT_TRUE(notMatches("", NotClassX));
609 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
610 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
611 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
612 EXPECT_TRUE(
613 notMatches("class Y {}; class Z {}; class X : public Y {};",
614 NotClassX));
615
616 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000617 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000618 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000619 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000620 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000621 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000622 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
623 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
624 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000625
626 DeclarationMatcher NamedNotRecord =
627 namedDecl(hasName("Foo"), unless(recordDecl()));
628 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
629 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000630}
631
632TEST(DeclarationMatcher, HasDescendant) {
633 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000634 recordDecl(
635 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000636 hasName("Z"));
637 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
638 EXPECT_TRUE(
639 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
640 EXPECT_TRUE(
641 matches("class Z { class A { class Y { class X {}; }; }; };",
642 ZDescendantClassX));
643 EXPECT_TRUE(
644 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
645 ZDescendantClassX));
646 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
647
648 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000649 recordDecl(
650 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000651 hasName("X"))),
652 hasName("Z"));
653 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
654 ZDescendantClassXHasClassY));
655 EXPECT_TRUE(
656 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
657 ZDescendantClassXHasClassY));
658 EXPECT_TRUE(notMatches(
659 "class Z {"
660 " class A {"
661 " class B {"
662 " class X {"
663 " class C {"
664 " class Y {};"
665 " };"
666 " };"
667 " }; "
668 " };"
669 "};", ZDescendantClassXHasClassY));
670
671 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000672 recordDecl(
673 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
674 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000675 hasName("Z"));
676 EXPECT_TRUE(
677 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
678 ZDescendantClassXDescendantClassY));
679 EXPECT_TRUE(matches(
680 "class Z {"
681 " class A {"
682 " class X {"
683 " class B {"
684 " class Y {};"
685 " };"
686 " class Y {};"
687 " };"
688 " };"
689 "};", ZDescendantClassXDescendantClassY));
690}
691
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000692TEST(DeclarationMatcher, HasDescendantMemoization) {
693 DeclarationMatcher CannotMemoize =
694 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
695 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
696}
697
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000698TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
699 auto Name = hasName("i");
700 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
701 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
702 // Matching VD first should not make a cache hit for RD.
703 EXPECT_TRUE(notMatches("void f() { int i; }",
704 decl(hasDescendant(VD), hasDescendant(RD))));
705 EXPECT_TRUE(notMatches("void f() { int i; }",
706 decl(hasDescendant(RD), hasDescendant(VD))));
707 // Not matching RD first should not make a cache hit for VD either.
708 EXPECT_TRUE(matches("void f() { int i; }",
709 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
710}
711
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000712TEST(DeclarationMatcher, HasAttr) {
713 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
714 decl(hasAttr(clang::attr::WarnUnused))));
715 EXPECT_FALSE(matches("struct X {};",
716 decl(hasAttr(clang::attr::WarnUnused))));
717}
718
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000719TEST(DeclarationMatcher, MatchCudaDecl) {
720 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
721 "void g() { f<<<1, 2>>>(); }",
722 CUDAKernelCallExpr()));
723 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000724 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000725 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000726 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000727 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000728 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000729}
730
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000731// Implements a run method that returns whether BoundNodes contains a
732// Decl bound to Id that can be dynamically cast to T.
733// Optionally checks that the check succeeded a specific number of times.
734template <typename T>
735class VerifyIdIsBoundTo : public BoundNodesCallback {
736public:
737 // Create an object that checks that a node of type \c T was bound to \c Id.
738 // Does not check for a certain number of matches.
739 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
740 : Id(Id), ExpectedCount(-1), Count(0) {}
741
742 // Create an object that checks that a node of type \c T was bound to \c Id.
743 // Checks that there were exactly \c ExpectedCount matches.
744 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
745 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
746
747 // Create an object that checks that a node of type \c T was bound to \c Id.
748 // Checks that there was exactly one match with the name \c ExpectedName.
749 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000750 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
751 int ExpectedCount = 1)
752 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
753 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000754
Craig Toppera798a9d2014-03-02 09:32:10 +0000755 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000756 if (ExpectedCount != -1)
757 EXPECT_EQ(ExpectedCount, Count);
758 if (!ExpectedName.empty())
759 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000760 Count = 0;
761 Name.clear();
762 }
763
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000764 ~VerifyIdIsBoundTo() override {
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000765 EXPECT_EQ(0, Count);
766 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000767 }
768
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000769 bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000770 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000771 if (Nodes->getNodeAs<T>(Id)) {
772 ++Count;
773 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
774 Name = Named->getNameAsString();
775 } else if (const NestedNameSpecifier *NNS =
776 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
777 llvm::raw_string_ostream OS(Name);
778 NNS->print(OS, PrintingPolicy(LangOptions()));
779 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000780 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
781 EXPECT_NE(M.end(), I);
782 if (I != M.end())
783 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000784 return true;
785 }
Craig Topper416fa342014-06-08 08:38:12 +0000786 EXPECT_TRUE(M.count(Id) == 0 ||
787 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000788 return false;
789 }
790
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000791 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000792 return run(Nodes);
793 }
794
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000795private:
796 const std::string Id;
797 const int ExpectedCount;
798 int Count;
799 const std::string ExpectedName;
800 std::string Name;
801};
802
803TEST(HasDescendant, MatchesDescendantTypes) {
804 EXPECT_TRUE(matches("void f() { int i = 3; }",
805 decl(hasDescendant(loc(builtinType())))));
806 EXPECT_TRUE(matches("void f() { int i = 3; }",
807 stmt(hasDescendant(builtinType()))));
808
809 EXPECT_TRUE(matches("void f() { int i = 3; }",
810 stmt(hasDescendant(loc(builtinType())))));
811 EXPECT_TRUE(matches("void f() { int i = 3; }",
812 stmt(hasDescendant(qualType(builtinType())))));
813
814 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
815 stmt(hasDescendant(isInteger()))));
816
817 EXPECT_TRUE(matchAndVerifyResultTrue(
818 "void f() { int a; float c; int d; int e; }",
819 functionDecl(forEachDescendant(
820 varDecl(hasDescendant(isInteger())).bind("x"))),
821 new VerifyIdIsBoundTo<Decl>("x", 3)));
822}
823
824TEST(HasDescendant, MatchesDescendantsOfTypes) {
825 EXPECT_TRUE(matches("void f() { int*** i; }",
826 qualType(hasDescendant(builtinType()))));
827 EXPECT_TRUE(matches("void f() { int*** i; }",
828 qualType(hasDescendant(
829 pointerType(pointee(builtinType()))))));
830 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000831 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000832
833 EXPECT_TRUE(matchAndVerifyResultTrue(
834 "void f() { int*** i; }",
835 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
836 new VerifyIdIsBoundTo<Type>("x", 2)));
837}
838
839TEST(Has, MatchesChildrenOfTypes) {
840 EXPECT_TRUE(matches("int i;",
841 varDecl(hasName("i"), has(isInteger()))));
842 EXPECT_TRUE(notMatches("int** i;",
843 varDecl(hasName("i"), has(isInteger()))));
844 EXPECT_TRUE(matchAndVerifyResultTrue(
845 "int (*f)(float, int);",
846 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
847 new VerifyIdIsBoundTo<QualType>("x", 2)));
848}
849
850TEST(Has, MatchesChildTypes) {
851 EXPECT_TRUE(matches(
852 "int* i;",
853 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
854 EXPECT_TRUE(notMatches(
855 "int* i;",
856 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
857}
858
Samuel Benzaquenc640ef52014-10-28 13:33:58 +0000859TEST(ValueDecl, Matches) {
860 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
861 valueDecl(hasType(asString("enum EnumType")))));
862 EXPECT_TRUE(matches("void FunctionDecl();",
863 valueDecl(hasType(asString("void (void)")))));
864}
865
Daniel Jasper1dad1832012-07-10 20:20:19 +0000866TEST(Enum, DoesNotMatchClasses) {
867 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
868}
869
870TEST(Enum, MatchesEnums) {
871 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
872}
873
874TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000875 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000876 EXPECT_TRUE(matches("enum X{ A };", Matcher));
877 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
878 EXPECT_TRUE(notMatches("enum X {};", Matcher));
879}
880
Manuel Klimek04616e42012-07-06 05:48:52 +0000881TEST(StatementMatcher, Has) {
882 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000883 expr(hasType(pointsTo(recordDecl(hasName("X")))),
884 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000885
886 EXPECT_TRUE(matches(
887 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
888 EXPECT_TRUE(notMatches(
889 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
890}
891
892TEST(StatementMatcher, HasDescendant) {
893 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000894 expr(hasType(pointsTo(recordDecl(hasName("X")))),
895 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000896
897 EXPECT_TRUE(matches(
898 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
899 HasDescendantVariableI));
900 EXPECT_TRUE(notMatches(
901 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
902 HasDescendantVariableI));
903}
904
905TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000906 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000907
908 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
909 EXPECT_TRUE(notMatches("class A {};", TypeA));
910
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000911 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000912
913 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
914 TypeDerivedFromA));
915 EXPECT_TRUE(notMatches("class A {};", TypeA));
916
917 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000918 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000919
920 EXPECT_TRUE(
921 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
Aaron Ballmanc129c692015-09-04 18:34:48 +0000922
923 EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }",
924 varDecl(hasType(namedDecl(hasName("S"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000925}
926
Manuel Klimek04616e42012-07-06 05:48:52 +0000927TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000928 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000929
930 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000931 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000932
933 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000934 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000935
936 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000937 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000938
939 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
940 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000941 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000942
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000943 StatementMatcher MethodX =
944 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000945
946 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
947 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000948 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000949}
950
951TEST(Matcher, BindTheSameNameInAlternatives) {
952 StatementMatcher matcher = anyOf(
953 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000954 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000955 hasRHS(integerLiteral(equals(0)))),
956 binaryOperator(hasOperatorName("+"),
957 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000958 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000959
960 EXPECT_TRUE(matchAndVerifyResultTrue(
961 // The first branch of the matcher binds x to 0 but then fails.
962 // The second branch binds x to f() and succeeds.
963 "int f() { return 0 + f(); }",
964 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000965 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000966}
967
Manuel Klimekfdf98762012-08-30 19:41:06 +0000968TEST(Matcher, BindsIDForMemoizedResults) {
969 // Using the same matcher in two match expressions will make memoization
970 // kick in.
971 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
972 EXPECT_TRUE(matchAndVerifyResultTrue(
973 "class A { class B { class X {}; }; };",
974 DeclarationMatcher(anyOf(
975 recordDecl(hasName("A"), hasDescendant(ClassX)),
976 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000977 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000978}
979
Daniel Jasper856194d02012-12-03 15:43:25 +0000980TEST(HasDeclaration, HasDeclarationOfEnumType) {
981 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
982 expr(hasType(pointsTo(
983 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
984}
985
Edwin Vaneed936452013-02-25 14:32:42 +0000986TEST(HasDeclaration, HasGetDeclTraitTest) {
987 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
988 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
989 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
990}
991
Edwin Vane2c197e02013-02-19 17:14:34 +0000992TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
993 EXPECT_TRUE(matches("typedef int X; X a;",
994 varDecl(hasName("a"),
995 hasType(typedefType(hasDeclaration(decl()))))));
996
997 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
998}
999
Edwin Vanef901b712013-02-25 14:49:29 +00001000TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
1001 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
1002 varDecl(hasType(templateSpecializationType(
1003 hasDeclaration(namedDecl(hasName("A"))))))));
1004}
1005
Manuel Klimek04616e42012-07-06 05:48:52 +00001006TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001007 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001008 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001009 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001010 EXPECT_TRUE(
1011 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001012 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001013 EXPECT_TRUE(
1014 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001015 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001016}
1017
1018TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001019 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001020 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001021 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001022 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001023 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001024 EXPECT_TRUE(
1025 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001026 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001027}
1028
1029TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001030 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001031 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001032 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001033 EXPECT_TRUE(
1034 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001035 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001036}
1037
1038TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001039 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001040 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001041 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001042 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001043 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001044}
1045
Manuel Klimekc16c6522013-06-20 13:08:29 +00001046TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1047 EXPECT_TRUE(matches("int x;",
1048 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1049
1050 // Make sure we don't crash on implicit constructors.
1051 EXPECT_TRUE(notMatches("class X {}; X x;",
1052 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1053}
1054
Manuel Klimek04616e42012-07-06 05:48:52 +00001055TEST(Matcher, Call) {
1056 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001057 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001058 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001059
1060 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1061 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1062
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001063 StatementMatcher MethodOnY =
1064 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001065
1066 EXPECT_TRUE(
1067 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1068 MethodOnY));
1069 EXPECT_TRUE(
1070 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1071 MethodOnY));
1072 EXPECT_TRUE(
1073 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1074 MethodOnY));
1075 EXPECT_TRUE(
1076 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1077 MethodOnY));
1078 EXPECT_TRUE(
1079 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1080 MethodOnY));
1081
1082 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001083 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001084
1085 EXPECT_TRUE(
1086 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1087 MethodOnYPointer));
1088 EXPECT_TRUE(
1089 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1090 MethodOnYPointer));
1091 EXPECT_TRUE(
1092 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1093 MethodOnYPointer));
1094 EXPECT_TRUE(
1095 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1096 MethodOnYPointer));
1097 EXPECT_TRUE(
1098 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1099 MethodOnYPointer));
1100}
1101
Daniel Jasper5901e472012-10-01 13:40:41 +00001102TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001103 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001104 lambdaExpr()));
1105}
1106
1107TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001108 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1109 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001110 forRangeStmt()));
1111 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1112 forRangeStmt()));
1113}
1114
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001115TEST(Matcher, SubstNonTypeTemplateParm) {
1116 EXPECT_FALSE(matches("template<int N>\n"
1117 "struct A { static const int n = 0; };\n"
1118 "struct B : public A<42> {};",
1119 substNonTypeTemplateParmExpr()));
1120 EXPECT_TRUE(matches("template<int N>\n"
1121 "struct A { static const int n = N; };\n"
1122 "struct B : public A<42> {};",
1123 substNonTypeTemplateParmExpr()));
1124}
1125
Daniel Jasper5901e472012-10-01 13:40:41 +00001126TEST(Matcher, UserDefinedLiteral) {
1127 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1128 " return i + 1;"
1129 "}"
1130 "char c = 'a'_inc;",
1131 userDefinedLiteral()));
1132}
1133
Daniel Jasper87c3d362012-09-20 14:12:57 +00001134TEST(Matcher, FlowControl) {
1135 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1136 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1137 continueStmt()));
1138 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1139 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1140 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1141}
1142
Daniel Jasper1dad1832012-07-10 20:20:19 +00001143TEST(HasType, MatchesAsString) {
1144 EXPECT_TRUE(
1145 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001146 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001147 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001148 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001149 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001150 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001151 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001152 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001153}
1154
Manuel Klimek04616e42012-07-06 05:48:52 +00001155TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001156 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001157 // Unary operator
1158 EXPECT_TRUE(matches("class Y { }; "
1159 "bool operator!(Y x) { return false; }; "
1160 "Y y; bool c = !y;", OpCall));
1161 // No match -- special operators like "new", "delete"
1162 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1163 // we need to figure out include paths in the test.
1164 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1165 // "class Y { }; "
1166 // "void *operator new(size_t size) { return 0; } "
1167 // "Y *y = new Y;", OpCall));
1168 EXPECT_TRUE(notMatches("class Y { }; "
1169 "void operator delete(void *p) { } "
1170 "void a() {Y *y = new Y; delete y;}", OpCall));
1171 // Binary operator
1172 EXPECT_TRUE(matches("class Y { }; "
1173 "bool operator&&(Y x, Y y) { return true; }; "
1174 "Y a; Y b; bool c = a && b;",
1175 OpCall));
1176 // No match -- normal operator, not an overloaded one.
1177 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1178 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1179}
1180
1181TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1182 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001183 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001184 EXPECT_TRUE(matches("class Y { }; "
1185 "bool operator&&(Y x, Y y) { return true; }; "
1186 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1187 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001188 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001189 EXPECT_TRUE(notMatches("class Y { }; "
1190 "bool operator&&(Y x, Y y) { return true; }; "
1191 "Y a; Y b; bool c = a && b;",
1192 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001193 StatementMatcher OpStarCall =
1194 operatorCallExpr(hasOverloadedOperatorName("*"));
1195 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1196 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001197 DeclarationMatcher ClassWithOpStar =
1198 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1199 EXPECT_TRUE(matches("class Y { int operator*(); };",
1200 ClassWithOpStar));
1201 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1202 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001203 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1204 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1205 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001206}
1207
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001208TEST(Matcher, NestedOverloadedOperatorCalls) {
1209 EXPECT_TRUE(matchAndVerifyResultTrue(
1210 "class Y { }; "
1211 "Y& operator&&(Y& x, Y& y) { return x; }; "
1212 "Y a; Y b; Y c; Y d = a && b && c;",
1213 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1214 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1215 EXPECT_TRUE(matches(
1216 "class Y { }; "
1217 "Y& operator&&(Y& x, Y& y) { return x; }; "
1218 "Y a; Y b; Y c; Y d = a && b && c;",
1219 operatorCallExpr(hasParent(operatorCallExpr()))));
1220 EXPECT_TRUE(matches(
1221 "class Y { }; "
1222 "Y& operator&&(Y& x, Y& y) { return x; }; "
1223 "Y a; Y b; Y c; Y d = a && b && c;",
1224 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1225}
1226
Manuel Klimek04616e42012-07-06 05:48:52 +00001227TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001228 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001229 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001230
1231 EXPECT_TRUE(
1232 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1233 MethodOnY));
1234 EXPECT_TRUE(
1235 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1236 MethodOnY));
1237 EXPECT_TRUE(
1238 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1239 MethodOnY));
1240 EXPECT_TRUE(
1241 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1242 MethodOnY));
1243 EXPECT_TRUE(
1244 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1245 MethodOnY));
1246
1247 EXPECT_TRUE(matches(
1248 "class Y {"
1249 " public: virtual void x();"
1250 "};"
1251 "class X : public Y {"
1252 " public: virtual void x();"
1253 "};"
1254 "void z() { X *x; x->Y::x(); }", MethodOnY));
1255}
1256
1257TEST(Matcher, VariableUsage) {
1258 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001259 declRefExpr(to(
1260 varDecl(hasInitializer(
1261 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001262
1263 EXPECT_TRUE(matches(
1264 "class Y {"
1265 " public:"
1266 " bool x() const;"
1267 "};"
1268 "void z(const Y &y) {"
1269 " bool b = y.x();"
1270 " if (b) {}"
1271 "}", Reference));
1272
1273 EXPECT_TRUE(notMatches(
1274 "class Y {"
1275 " public:"
1276 " bool x() const;"
1277 "};"
1278 "void z(const Y &y) {"
1279 " bool b = y.x();"
1280 "}", Reference));
1281}
1282
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001283TEST(Matcher, VarDecl_Storage) {
1284 auto M = varDecl(hasName("X"), hasLocalStorage());
1285 EXPECT_TRUE(matches("void f() { int X; }", M));
1286 EXPECT_TRUE(notMatches("int X;", M));
1287 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1288
1289 M = varDecl(hasName("X"), hasGlobalStorage());
1290 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1291 EXPECT_TRUE(matches("int X;", M));
1292 EXPECT_TRUE(matches("void f() { static int X; }", M));
1293}
1294
Manuel Klimek61379422012-12-04 14:42:08 +00001295TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001296 EXPECT_TRUE(matches(
1297 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001298 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001299}
1300
Manuel Klimek04616e42012-07-06 05:48:52 +00001301TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001302 StatementMatcher CallOnVariableY =
1303 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001304
1305 EXPECT_TRUE(matches(
1306 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1307 EXPECT_TRUE(matches(
1308 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1309 EXPECT_TRUE(matches(
1310 "class Y { public: void x(); };"
1311 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1312 EXPECT_TRUE(matches(
1313 "class Y { public: void x(); };"
1314 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1315 EXPECT_TRUE(notMatches(
1316 "class Y { public: void x(); };"
1317 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1318 CallOnVariableY));
1319}
1320
Daniel Jasper1dad1832012-07-10 20:20:19 +00001321TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1322 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1323 unaryExprOrTypeTraitExpr()));
1324 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1325 alignOfExpr(anything())));
1326 // FIXME: Uncomment once alignof is enabled.
1327 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1328 // unaryExprOrTypeTraitExpr()));
1329 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1330 // sizeOfExpr()));
1331}
1332
1333TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1334 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1335 hasArgumentOfType(asString("int")))));
1336 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1337 hasArgumentOfType(asString("float")))));
1338 EXPECT_TRUE(matches(
1339 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001340 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001341 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001342 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001343}
1344
Manuel Klimek04616e42012-07-06 05:48:52 +00001345TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001346 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001347}
1348
1349TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001350 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001351}
1352
1353TEST(MemberExpression, MatchesVariable) {
1354 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001355 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001356 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001357 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001358 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001359 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001360}
1361
1362TEST(MemberExpression, MatchesStaticVariable) {
1363 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001364 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001365 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001366 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001367 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001368 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001369}
1370
Daniel Jasper4e566c42012-07-12 08:50:38 +00001371TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001372 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1373 EXPECT_TRUE(matches(
1374 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1375 callExpr(hasArgument(0, declRefExpr(
1376 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001377}
1378
1379TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001380 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001381 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001382 callExpr(hasArgument(0, declRefExpr(
1383 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001384}
1385
Manuel Klimek04616e42012-07-06 05:48:52 +00001386TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1387 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001388 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001389 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001390 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001391 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001392 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001393}
1394
1395TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1396 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001397 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001398 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001399 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001400 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001401 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001402}
1403
1404TEST(IsArrow, MatchesMemberCallsViaArrow) {
1405 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001406 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001407 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001408 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001409 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001410 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001411}
1412
1413TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001414 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001415
1416 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1417 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001418
1419 CallMethodX = callExpr(callee(conversionDecl()));
1420 EXPECT_TRUE(
1421 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1422 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1423 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001424}
1425
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001426TEST(ConversionDeclaration, IsExplicit) {
1427 EXPECT_TRUE(matches("struct S { explicit operator int(); };",
1428 conversionDecl(isExplicit())));
1429 EXPECT_TRUE(notMatches("struct S { operator int(); };",
1430 conversionDecl(isExplicit())));
1431}
1432
Manuel Klimek04616e42012-07-06 05:48:52 +00001433TEST(Callee, MatchesMemberExpressions) {
1434 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001435 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001436 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001437 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001438}
1439
1440TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001441 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001442
1443 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1444 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1445
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001446 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1447 llvm::Triple::Win32) {
1448 // FIXME: Make this work for MSVC.
1449 // Dependent contexts, but a non-dependent call.
1450 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1451 CallFunctionF));
1452 EXPECT_TRUE(
1453 matches("void f(); template <int N> struct S { void g() { f(); } };",
1454 CallFunctionF));
1455 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001456
1457 // Depedent calls don't match.
1458 EXPECT_TRUE(
1459 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1460 CallFunctionF));
1461 EXPECT_TRUE(
1462 notMatches("void f(int);"
1463 "template <typename T> struct S { void g(T t) { f(t); } };",
1464 CallFunctionF));
1465}
1466
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001467TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1468 EXPECT_TRUE(
1469 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001470 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001471}
1472
1473TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1474 EXPECT_TRUE(
1475 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001476 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001477}
1478
1479TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1480 EXPECT_TRUE(
1481 notMatches("void g(); template <typename T> void f(T t) {}"
1482 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001483 functionTemplateDecl(hasName("f"),
1484 hasDescendant(declRefExpr(to(
1485 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001486}
1487
Manuel Klimek04616e42012-07-06 05:48:52 +00001488TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001489 StatementMatcher CallArgumentY = callExpr(
1490 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001491
1492 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1493 EXPECT_TRUE(
1494 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1495 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1496
Daniel Jasper848cbe12012-09-18 13:09:13 +00001497 StatementMatcher WrongIndex = callExpr(
1498 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001499 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1500}
1501
1502TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001503 StatementMatcher CallArgumentY = callExpr(
1504 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001505 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1506 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1507 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1508}
1509
1510TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001511 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001512
1513 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1514 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1515 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1516}
1517
Daniel Jasper9f501292012-12-04 11:54:27 +00001518TEST(Matcher, ParameterCount) {
1519 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1520 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1521 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1522 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1523 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1524}
1525
Manuel Klimek04616e42012-07-06 05:48:52 +00001526TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001527 DeclarationMatcher ReferenceClassX = varDecl(
1528 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001529 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1530 ReferenceClassX));
1531 EXPECT_TRUE(
1532 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001533 // The match here is on the implicit copy constructor code for
1534 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001535 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001536 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1537 EXPECT_TRUE(
1538 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001539 EXPECT_TRUE(
1540 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1541}
1542
Edwin Vane0a4836e2013-03-06 17:02:57 +00001543TEST(QualType, hasCanonicalType) {
1544 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1545 "int a;"
1546 "int_ref b = a;",
1547 varDecl(hasType(qualType(referenceType())))));
1548 EXPECT_TRUE(
1549 matches("typedef int &int_ref;"
1550 "int a;"
1551 "int_ref b = a;",
1552 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1553}
1554
Edwin Vane119d3df2013-04-02 18:15:55 +00001555TEST(QualType, hasLocalQualifiers) {
1556 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1557 varDecl(hasType(hasLocalQualifiers()))));
1558 EXPECT_TRUE(matches("int *const j = nullptr;",
1559 varDecl(hasType(hasLocalQualifiers()))));
1560 EXPECT_TRUE(matches("int *volatile k;",
1561 varDecl(hasType(hasLocalQualifiers()))));
1562 EXPECT_TRUE(notMatches("int m;",
1563 varDecl(hasType(hasLocalQualifiers()))));
1564}
1565
Manuel Klimek04616e42012-07-06 05:48:52 +00001566TEST(HasParameter, CallsInnerMatcher) {
1567 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001568 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001569 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001570 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001571}
1572
1573TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1574 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001575 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001576}
1577
1578TEST(HasType, MatchesParameterVariableTypesStrictly) {
1579 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001580 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001581 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001582 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001583 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001584 methodDecl(hasParameter(0,
1585 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001586 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001587 methodDecl(hasParameter(0,
1588 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001589}
1590
1591TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1592 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001593 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001594 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001595 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001596}
1597
Daniel Jasper1dad1832012-07-10 20:20:19 +00001598TEST(Returns, MatchesReturnTypes) {
1599 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001600 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001601 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001602 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001603 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001604 functionDecl(returns(hasDeclaration(
1605 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001606}
1607
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001608TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001609 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1610 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1611 functionDecl(isExternC())));
1612 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001613}
1614
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001615TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1616 EXPECT_TRUE(
1617 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1618 EXPECT_TRUE(matches("void Func() = delete;",
1619 functionDecl(hasName("Func"), isDeleted())));
1620}
1621
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001622TEST(isConstexpr, MatchesConstexprDeclarations) {
1623 EXPECT_TRUE(matches("constexpr int foo = 42;",
1624 varDecl(hasName("foo"), isConstexpr())));
1625 EXPECT_TRUE(matches("constexpr int bar();",
1626 functionDecl(hasName("bar"), isConstexpr())));
1627}
1628
Manuel Klimek04616e42012-07-06 05:48:52 +00001629TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1630 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001631 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001632}
1633
1634TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1635 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001636 methodDecl(hasAnyParameter(hasType(pointsTo(
1637 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001638}
1639
Alp Toker8db6e7a2014-01-05 06:38:57 +00001640TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001641 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001642 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001643 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001644 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001645}
1646
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001647TEST(Matcher, MatchesClassTemplateSpecialization) {
1648 EXPECT_TRUE(matches("template<typename T> struct A {};"
1649 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001650 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001651 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001652 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001653 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001654 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001655}
1656
Manuel Klimekc16c6522013-06-20 13:08:29 +00001657TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1658 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1659 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1660}
1661
1662TEST(ParmVarDecl, MatchesParmVars) {
1663 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1664 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1665}
1666
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001667TEST(Matcher, MatchesTypeTemplateArgument) {
1668 EXPECT_TRUE(matches(
1669 "template<typename T> struct B {};"
1670 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001671 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001672 asString("int"))))));
1673}
1674
1675TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1676 EXPECT_TRUE(matches(
1677 "struct B { int next; };"
1678 "template<int(B::*next_ptr)> struct A {};"
1679 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001680 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1681 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001682
1683 EXPECT_TRUE(notMatches(
1684 "template <typename T> struct A {};"
1685 "A<int> a;",
1686 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1687 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001688
1689 EXPECT_TRUE(matches(
1690 "struct B { int next; };"
1691 "template<int(B::*next_ptr)> struct A {};"
1692 "A<&B::next> a;",
1693 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1694 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1695
1696 EXPECT_TRUE(notMatches(
1697 "template <typename T> struct A {};"
1698 "A<int> a;",
1699 templateSpecializationType(hasAnyTemplateArgument(
1700 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001701}
1702
1703TEST(Matcher, MatchesSpecificArgument) {
1704 EXPECT_TRUE(matches(
1705 "template<typename T, typename U> class A {};"
1706 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001707 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001708 1, refersToType(asString("int"))))));
1709 EXPECT_TRUE(notMatches(
1710 "template<typename T, typename U> class A {};"
1711 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001712 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001713 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001714
1715 EXPECT_TRUE(matches(
1716 "template<typename T, typename U> class A {};"
1717 "A<bool, int> a;",
1718 templateSpecializationType(hasTemplateArgument(
1719 1, refersToType(asString("int"))))));
1720 EXPECT_TRUE(notMatches(
1721 "template<typename T, typename U> class A {};"
1722 "A<int, bool> a;",
1723 templateSpecializationType(hasTemplateArgument(
1724 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001725}
1726
Manuel Klimek7735e402014-10-09 13:06:22 +00001727TEST(TemplateArgument, Matches) {
1728 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1729 classTemplateSpecializationDecl(
1730 hasAnyTemplateArgument(templateArgument()))));
1731 EXPECT_TRUE(matches(
1732 "template<typename T> struct C {}; C<int> c;",
1733 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1734}
1735
1736TEST(TemplateArgumentCountIs, Matches) {
1737 EXPECT_TRUE(
1738 matches("template<typename T> struct C {}; C<int> c;",
1739 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1740 EXPECT_TRUE(
1741 notMatches("template<typename T> struct C {}; C<int> c;",
1742 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1743
1744 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1745 templateSpecializationType(templateArgumentCountIs(1))));
1746 EXPECT_TRUE(
1747 notMatches("template<typename T> struct C {}; C<int> c;",
1748 templateSpecializationType(templateArgumentCountIs(2))));
1749}
1750
1751TEST(IsIntegral, Matches) {
1752 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1753 classTemplateSpecializationDecl(
1754 hasAnyTemplateArgument(isIntegral()))));
1755 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1756 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1757 templateArgument(isIntegral())))));
1758}
1759
1760TEST(RefersToIntegralType, Matches) {
1761 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1762 classTemplateSpecializationDecl(
1763 hasAnyTemplateArgument(refersToIntegralType(
1764 asString("int"))))));
1765 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1766 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1767 refersToIntegralType(asString("int"))))));
1768}
1769
1770TEST(EqualsIntegralValue, Matches) {
1771 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1772 classTemplateSpecializationDecl(
1773 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1774 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1775 classTemplateSpecializationDecl(
1776 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1777 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1778 classTemplateSpecializationDecl(
1779 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1780 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1781 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1782 equalsIntegralValue("0042")))));
1783}
1784
Daniel Jasper639522c2013-02-25 12:02:08 +00001785TEST(Matcher, MatchesAccessSpecDecls) {
1786 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1787 EXPECT_TRUE(
1788 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1789 EXPECT_TRUE(
1790 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1791 EXPECT_TRUE(
1792 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1793
1794 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1795}
1796
Aaron Ballman41143bb2015-07-24 12:35:41 +00001797TEST(Matcher, MatchesFinal) {
1798 EXPECT_TRUE(matches("class X final {};", recordDecl(isFinal())));
1799 EXPECT_TRUE(matches("class X { virtual void f() final; };",
1800 methodDecl(isFinal())));
1801 EXPECT_TRUE(notMatches("class X {};", recordDecl(isFinal())));
1802 EXPECT_TRUE(notMatches("class X { virtual void f(); };",
1803 methodDecl(isFinal())));
1804}
1805
Edwin Vane37ee1d72013-04-09 20:46:36 +00001806TEST(Matcher, MatchesVirtualMethod) {
1807 EXPECT_TRUE(matches("class X { virtual int f(); };",
1808 methodDecl(isVirtual(), hasName("::X::f"))));
1809 EXPECT_TRUE(notMatches("class X { int f(); };",
1810 methodDecl(isVirtual())));
1811}
1812
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001813TEST(Matcher, MatchesPureMethod) {
1814 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1815 methodDecl(isPure(), hasName("::X::f"))));
1816 EXPECT_TRUE(notMatches("class X { int f(); };",
1817 methodDecl(isPure())));
1818}
1819
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001820TEST(Matcher, MatchesConstMethod) {
1821 EXPECT_TRUE(matches("struct A { void foo() const; };",
1822 methodDecl(isConst())));
1823 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1824 methodDecl(isConst())));
1825}
1826
Edwin Vane37ee1d72013-04-09 20:46:36 +00001827TEST(Matcher, MatchesOverridingMethod) {
1828 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1829 "class Y : public X { int f(); };",
1830 methodDecl(isOverride(), hasName("::Y::f"))));
1831 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1832 "class Y : public X { int f(); };",
1833 methodDecl(isOverride(), hasName("::X::f"))));
1834 EXPECT_TRUE(notMatches("class X { int f(); }; "
1835 "class Y : public X { int f(); };",
1836 methodDecl(isOverride())));
1837 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1838 methodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001839 EXPECT_TRUE(
1840 matches("template <typename Base> struct Y : Base { void f() override;};",
1841 methodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001842}
1843
Manuel Klimek04616e42012-07-06 05:48:52 +00001844TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001845 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001846
1847 EXPECT_TRUE(
1848 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1849 EXPECT_TRUE(
1850 matches("class X { public: X(); }; void x() { X x = X(); }",
1851 Constructor));
1852 EXPECT_TRUE(
1853 matches("class X { public: X(int); }; void x() { X x = 0; }",
1854 Constructor));
1855 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1856}
1857
1858TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001859 StatementMatcher Constructor = constructExpr(
1860 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001861
1862 EXPECT_TRUE(
1863 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1864 Constructor));
1865 EXPECT_TRUE(
1866 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1867 Constructor));
1868 EXPECT_TRUE(
1869 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1870 Constructor));
1871 EXPECT_TRUE(
1872 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1873 Constructor));
1874
Daniel Jasper848cbe12012-09-18 13:09:13 +00001875 StatementMatcher WrongIndex = constructExpr(
1876 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001877 EXPECT_TRUE(
1878 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1879 WrongIndex));
1880}
1881
1882TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001883 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001884
1885 EXPECT_TRUE(
1886 matches("class X { public: X(int); }; void x() { X x(0); }",
1887 Constructor1Arg));
1888 EXPECT_TRUE(
1889 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1890 Constructor1Arg));
1891 EXPECT_TRUE(
1892 matches("class X { public: X(int); }; void x() { X x = 0; }",
1893 Constructor1Arg));
1894 EXPECT_TRUE(
1895 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1896 Constructor1Arg));
1897}
1898
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001899TEST(Matcher, ConstructorListInitialization) {
1900 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1901
1902 EXPECT_TRUE(
1903 matches("class X { public: X(int); }; void x() { X x{0}; }",
1904 ConstructorListInit));
1905 EXPECT_FALSE(
1906 matches("class X { public: X(int); }; void x() { X x(0); }",
1907 ConstructorListInit));
1908}
1909
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001910TEST(Matcher,ThisExpr) {
1911 EXPECT_TRUE(
1912 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1913 EXPECT_TRUE(
1914 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1915}
1916
Manuel Klimek04616e42012-07-06 05:48:52 +00001917TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001918 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001919
1920 std::string ClassString = "class string { public: string(); ~string(); }; ";
1921
1922 EXPECT_TRUE(
1923 matches(ClassString +
1924 "string GetStringByValue();"
1925 "void FunctionTakesString(string s);"
1926 "void run() { FunctionTakesString(GetStringByValue()); }",
1927 TempExpression));
1928
1929 EXPECT_TRUE(
1930 notMatches(ClassString +
1931 "string* GetStringPointer(); "
1932 "void FunctionTakesStringPtr(string* s);"
1933 "void run() {"
1934 " string* s = GetStringPointer();"
1935 " FunctionTakesStringPtr(GetStringPointer());"
1936 " FunctionTakesStringPtr(s);"
1937 "}",
1938 TempExpression));
1939
1940 EXPECT_TRUE(
1941 notMatches("class no_dtor {};"
1942 "no_dtor GetObjByValue();"
1943 "void ConsumeObj(no_dtor param);"
1944 "void run() { ConsumeObj(GetObjByValue()); }",
1945 TempExpression));
1946}
1947
Sam Panzer68a35af2012-08-24 22:04:44 +00001948TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1949 std::string ClassString =
1950 "class string { public: string(); int length(); }; ";
1951
1952 EXPECT_TRUE(
1953 matches(ClassString +
1954 "string GetStringByValue();"
1955 "void FunctionTakesString(string s);"
1956 "void run() { FunctionTakesString(GetStringByValue()); }",
1957 materializeTemporaryExpr()));
1958
1959 EXPECT_TRUE(
1960 notMatches(ClassString +
1961 "string* GetStringPointer(); "
1962 "void FunctionTakesStringPtr(string* s);"
1963 "void run() {"
1964 " string* s = GetStringPointer();"
1965 " FunctionTakesStringPtr(GetStringPointer());"
1966 " FunctionTakesStringPtr(s);"
1967 "}",
1968 materializeTemporaryExpr()));
1969
1970 EXPECT_TRUE(
1971 notMatches(ClassString +
1972 "string GetStringByValue();"
1973 "void run() { int k = GetStringByValue().length(); }",
1974 materializeTemporaryExpr()));
1975
1976 EXPECT_TRUE(
1977 notMatches(ClassString +
1978 "string GetStringByValue();"
1979 "void run() { GetStringByValue(); }",
1980 materializeTemporaryExpr()));
1981}
1982
Manuel Klimek04616e42012-07-06 05:48:52 +00001983TEST(ConstructorDeclaration, SimpleCase) {
1984 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001985 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001986 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001987 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001988}
1989
1990TEST(ConstructorDeclaration, IsImplicit) {
1991 // This one doesn't match because the constructor is not added by the
1992 // compiler (it is not needed).
1993 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001994 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001995 // The compiler added the implicit default constructor.
1996 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001997 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001998 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001999 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00002000 // The compiler added an implicit assignment operator.
2001 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
2002 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002003}
2004
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002005TEST(ConstructorDeclaration, IsExplicit) {
2006 EXPECT_TRUE(matches("struct S { explicit S(int); };",
2007 constructorDecl(isExplicit())));
2008 EXPECT_TRUE(notMatches("struct S { S(int); };",
2009 constructorDecl(isExplicit())));
2010}
2011
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002012TEST(ConstructorDeclaration, Kinds) {
2013 EXPECT_TRUE(matches("struct S { S(); };",
2014 constructorDecl(isDefaultConstructor())));
2015 EXPECT_TRUE(notMatches("struct S { S(); };",
2016 constructorDecl(isCopyConstructor())));
2017 EXPECT_TRUE(notMatches("struct S { S(); };",
2018 constructorDecl(isMoveConstructor())));
2019
2020 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
2021 constructorDecl(isDefaultConstructor())));
2022 EXPECT_TRUE(matches("struct S { S(const S&); };",
2023 constructorDecl(isCopyConstructor())));
2024 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
2025 constructorDecl(isMoveConstructor())));
2026
2027 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
2028 constructorDecl(isDefaultConstructor())));
2029 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
2030 constructorDecl(isCopyConstructor())));
2031 EXPECT_TRUE(matches("struct S { S(S&&); };",
2032 constructorDecl(isMoveConstructor())));
2033}
2034
Daniel Jasper1dad1832012-07-10 20:20:19 +00002035TEST(DestructorDeclaration, MatchesVirtualDestructor) {
2036 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002037 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002038}
2039
2040TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002041 EXPECT_TRUE(notMatches("class Foo {};",
2042 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002043}
2044
Manuel Klimek04616e42012-07-06 05:48:52 +00002045TEST(HasAnyConstructorInitializer, SimpleCase) {
2046 EXPECT_TRUE(notMatches(
2047 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002048 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002049 EXPECT_TRUE(matches(
2050 "class Foo {"
2051 " Foo() : foo_() { }"
2052 " int foo_;"
2053 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002054 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002055}
2056
2057TEST(HasAnyConstructorInitializer, ForField) {
2058 static const char Code[] =
2059 "class Baz { };"
2060 "class Foo {"
2061 " Foo() : foo_() { }"
2062 " Baz foo_;"
2063 " Baz bar_;"
2064 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002065 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
2066 forField(hasType(recordDecl(hasName("Baz"))))))));
2067 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002068 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002069 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
2070 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002071}
2072
2073TEST(HasAnyConstructorInitializer, WithInitializer) {
2074 static const char Code[] =
2075 "class Foo {"
2076 " Foo() : foo_(0) { }"
2077 " int foo_;"
2078 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002079 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002080 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002081 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002082 withInitializer(integerLiteral(equals(1)))))));
2083}
2084
2085TEST(HasAnyConstructorInitializer, IsWritten) {
2086 static const char Code[] =
2087 "struct Bar { Bar(){} };"
2088 "class Foo {"
2089 " Foo() : foo_() { }"
2090 " Bar foo_;"
2091 " Bar bar_;"
2092 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002093 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002094 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002095 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002096 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002097 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002098 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2099}
2100
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002101TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
2102 static const char Code[] =
2103 "struct B {};"
2104 "struct D : B {"
2105 " int I;"
2106 " D(int i) : I(i) {}"
2107 "};"
2108 "struct E : B {"
2109 " E() : B() {}"
2110 "};";
2111 EXPECT_TRUE(matches(Code, constructorDecl(allOf(
2112 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2113 hasName("E")))));
2114 EXPECT_TRUE(notMatches(Code, constructorDecl(allOf(
2115 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2116 hasName("D")))));
Aaron Ballmaned455d42015-08-11 20:42:00 +00002117 EXPECT_TRUE(matches(Code, constructorDecl(allOf(
2118 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2119 hasName("D")))));
2120 EXPECT_TRUE(notMatches(Code, constructorDecl(allOf(
2121 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2122 hasName("E")))));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002123}
2124
Manuel Klimek04616e42012-07-06 05:48:52 +00002125TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002126 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002127
2128 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2129 EXPECT_TRUE(
2130 matches("class X { public: X(); }; void x() { new X(); }", New));
2131 EXPECT_TRUE(
2132 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2133 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2134}
2135
2136TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002137 StatementMatcher New = constructExpr(
2138 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002139
2140 EXPECT_TRUE(
2141 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2142 New));
2143 EXPECT_TRUE(
2144 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2145 New));
2146 EXPECT_TRUE(
2147 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2148 New));
2149
Daniel Jasper848cbe12012-09-18 13:09:13 +00002150 StatementMatcher WrongIndex = constructExpr(
2151 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002152 EXPECT_TRUE(
2153 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2154 WrongIndex));
2155}
2156
2157TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002158 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002159
2160 EXPECT_TRUE(
2161 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2162 EXPECT_TRUE(
2163 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2164 New));
2165}
2166
Daniel Jasper1dad1832012-07-10 20:20:19 +00002167TEST(Matcher, DeleteExpression) {
2168 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002169 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002170}
2171
Manuel Klimek04616e42012-07-06 05:48:52 +00002172TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002173 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002174
2175 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2176 EXPECT_TRUE(
2177 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2178 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2179}
2180
2181TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002182 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002183 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2184 // wide string
2185 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2186 // with escaped characters
2187 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2188 // no matching -- though the data type is the same, there is no string literal
2189 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2190}
2191
2192TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002193 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002194 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2195 // wide character
2196 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2197 // wide character, Hex encoded, NOT MATCHED!
2198 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2199 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2200}
2201
2202TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002203 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002204 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2205 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2206 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2207 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2208
2209 // Non-matching cases (character literals, float and double)
2210 EXPECT_TRUE(notMatches("int i = L'a';",
2211 HasIntLiteral)); // this is actually a character
2212 // literal cast to int
2213 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2214 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2215 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2216}
2217
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002218TEST(Matcher, FloatLiterals) {
2219 StatementMatcher HasFloatLiteral = floatLiteral();
2220 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2221 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2222 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2223 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2224 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002225 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2226 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2227 EXPECT_TRUE(
2228 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002229
2230 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002231 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2232 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2233 EXPECT_TRUE(
2234 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002235}
2236
Daniel Jasper5901e472012-10-01 13:40:41 +00002237TEST(Matcher, NullPtrLiteral) {
2238 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2239}
2240
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002241TEST(Matcher, GNUNullExpr) {
2242 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2243}
2244
Daniel Jasper87c3d362012-09-20 14:12:57 +00002245TEST(Matcher, AsmStatement) {
2246 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2247}
2248
Manuel Klimek04616e42012-07-06 05:48:52 +00002249TEST(Matcher, Conditions) {
2250 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2251
2252 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2253 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2254 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2255 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2256 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2257}
2258
Manuel Klimek909b5c942014-05-27 10:04:12 +00002259TEST(IfStmt, ChildTraversalMatchers) {
2260 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2261 ifStmt(hasThen(boolLiteral(equals(true))))));
2262 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2263 ifStmt(hasThen(boolLiteral(equals(true))))));
2264 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2265 ifStmt(hasElse(boolLiteral(equals(true))))));
2266 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2267 ifStmt(hasElse(boolLiteral(equals(true))))));
2268}
2269
Manuel Klimek04616e42012-07-06 05:48:52 +00002270TEST(MatchBinaryOperator, HasOperatorName) {
2271 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2272
2273 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2274 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2275}
2276
2277TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2278 StatementMatcher OperatorTrueFalse =
2279 binaryOperator(hasLHS(boolLiteral(equals(true))),
2280 hasRHS(boolLiteral(equals(false))));
2281
2282 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2283 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2284 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2285}
2286
2287TEST(MatchBinaryOperator, HasEitherOperand) {
2288 StatementMatcher HasOperand =
2289 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2290
2291 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2292 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2293 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2294}
2295
2296TEST(Matcher, BinaryOperatorTypes) {
2297 // Integration test that verifies the AST provides all binary operators in
2298 // a way we expect.
2299 // FIXME: Operator ','
2300 EXPECT_TRUE(
2301 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2302 EXPECT_TRUE(
2303 matches("bool b; bool c = (b = true);",
2304 binaryOperator(hasOperatorName("="))));
2305 EXPECT_TRUE(
2306 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2307 EXPECT_TRUE(
2308 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2309 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2310 EXPECT_TRUE(
2311 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2312 EXPECT_TRUE(
2313 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2314 EXPECT_TRUE(
2315 matches("int i = 1; int j = (i <<= 2);",
2316 binaryOperator(hasOperatorName("<<="))));
2317 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2318 EXPECT_TRUE(
2319 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2320 EXPECT_TRUE(
2321 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2322 EXPECT_TRUE(
2323 matches("int i = 1; int j = (i >>= 2);",
2324 binaryOperator(hasOperatorName(">>="))));
2325 EXPECT_TRUE(
2326 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2327 EXPECT_TRUE(
2328 matches("int i = 42; int j = (i ^= 42);",
2329 binaryOperator(hasOperatorName("^="))));
2330 EXPECT_TRUE(
2331 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2332 EXPECT_TRUE(
2333 matches("int i = 42; int j = (i %= 42);",
2334 binaryOperator(hasOperatorName("%="))));
2335 EXPECT_TRUE(
2336 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2337 EXPECT_TRUE(
2338 matches("bool b = true && false;",
2339 binaryOperator(hasOperatorName("&&"))));
2340 EXPECT_TRUE(
2341 matches("bool b = true; bool c = (b &= false);",
2342 binaryOperator(hasOperatorName("&="))));
2343 EXPECT_TRUE(
2344 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2345 EXPECT_TRUE(
2346 matches("bool b = true || false;",
2347 binaryOperator(hasOperatorName("||"))));
2348 EXPECT_TRUE(
2349 matches("bool b = true; bool c = (b |= false);",
2350 binaryOperator(hasOperatorName("|="))));
2351 EXPECT_TRUE(
2352 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2353 EXPECT_TRUE(
2354 matches("int i = 42; int j = (i *= 23);",
2355 binaryOperator(hasOperatorName("*="))));
2356 EXPECT_TRUE(
2357 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2358 EXPECT_TRUE(
2359 matches("int i = 42; int j = (i /= 23);",
2360 binaryOperator(hasOperatorName("/="))));
2361 EXPECT_TRUE(
2362 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2363 EXPECT_TRUE(
2364 matches("int i = 42; int j = (i += 23);",
2365 binaryOperator(hasOperatorName("+="))));
2366 EXPECT_TRUE(
2367 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2368 EXPECT_TRUE(
2369 matches("int i = 42; int j = (i -= 23);",
2370 binaryOperator(hasOperatorName("-="))));
2371 EXPECT_TRUE(
2372 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2373 binaryOperator(hasOperatorName("->*"))));
2374 EXPECT_TRUE(
2375 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2376 binaryOperator(hasOperatorName(".*"))));
2377
2378 // Member expressions as operators are not supported in matches.
2379 EXPECT_TRUE(
2380 notMatches("struct A { void x(A *a) { a->x(this); } };",
2381 binaryOperator(hasOperatorName("->"))));
2382
2383 // Initializer assignments are not represented as operator equals.
2384 EXPECT_TRUE(
2385 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2386
2387 // Array indexing is not represented as operator.
2388 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2389
2390 // Overloaded operators do not match at all.
2391 EXPECT_TRUE(notMatches(
2392 "struct A { bool operator&&(const A &a) const { return false; } };"
2393 "void x() { A a, b; a && b; }",
2394 binaryOperator()));
2395}
2396
2397TEST(MatchUnaryOperator, HasOperatorName) {
2398 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2399
2400 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2401 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2402}
2403
2404TEST(MatchUnaryOperator, HasUnaryOperand) {
2405 StatementMatcher OperatorOnFalse =
2406 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2407
2408 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2409 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2410}
2411
2412TEST(Matcher, UnaryOperatorTypes) {
2413 // Integration test that verifies the AST provides all unary operators in
2414 // a way we expect.
2415 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2416 EXPECT_TRUE(
2417 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2418 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2419 EXPECT_TRUE(
2420 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2421 EXPECT_TRUE(
2422 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2423 EXPECT_TRUE(
2424 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2425 EXPECT_TRUE(
2426 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2427 EXPECT_TRUE(
2428 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2429 EXPECT_TRUE(
2430 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2431 EXPECT_TRUE(
2432 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2433
2434 // We don't match conversion operators.
2435 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2436
2437 // Function calls are not represented as operator.
2438 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2439
2440 // Overloaded operators do not match at all.
2441 // FIXME: We probably want to add that.
2442 EXPECT_TRUE(notMatches(
2443 "struct A { bool operator!() const { return false; } };"
2444 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2445}
2446
2447TEST(Matcher, ConditionalOperator) {
2448 StatementMatcher Conditional = conditionalOperator(
2449 hasCondition(boolLiteral(equals(true))),
2450 hasTrueExpression(boolLiteral(equals(false))));
2451
2452 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2453 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2454 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2455
2456 StatementMatcher ConditionalFalse = conditionalOperator(
2457 hasFalseExpression(boolLiteral(equals(false))));
2458
2459 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2460 EXPECT_TRUE(
2461 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2462}
2463
Daniel Jasper1dad1832012-07-10 20:20:19 +00002464TEST(ArraySubscriptMatchers, ArraySubscripts) {
2465 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2466 arraySubscriptExpr()));
2467 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2468 arraySubscriptExpr()));
2469}
2470
2471TEST(ArraySubscriptMatchers, ArrayIndex) {
2472 EXPECT_TRUE(matches(
2473 "int i[2]; void f() { i[1] = 1; }",
2474 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2475 EXPECT_TRUE(matches(
2476 "int i[2]; void f() { 1[i] = 1; }",
2477 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2478 EXPECT_TRUE(notMatches(
2479 "int i[2]; void f() { i[1] = 1; }",
2480 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2481}
2482
2483TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2484 EXPECT_TRUE(matches(
2485 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002486 arraySubscriptExpr(hasBase(implicitCastExpr(
2487 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002488}
2489
Manuel Klimek04616e42012-07-06 05:48:52 +00002490TEST(Matcher, HasNameSupportsNamespaces) {
2491 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002492 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002493 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002494 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002495 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002496 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002497 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002498 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002499 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002500 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002501 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002502 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002503 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002504 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002505 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002506 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002507 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002508 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002509 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002510 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002511 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002512 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002513 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002514 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002515}
2516
2517TEST(Matcher, HasNameSupportsOuterClasses) {
2518 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002519 matches("class A { class B { class C; }; };",
2520 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002521 EXPECT_TRUE(
2522 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002523 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002524 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002525 matches("class A { class B { class C; }; };",
2526 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002527 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002528 matches("class A { class B { class C; }; };",
2529 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002530 EXPECT_TRUE(
2531 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002532 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002533 EXPECT_TRUE(
2534 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002535 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002536 EXPECT_TRUE(
2537 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002538 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002539 EXPECT_TRUE(
2540 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002541 recordDecl(hasName("::C"))));
2542 EXPECT_TRUE(
2543 notMatches("class A { class B { class C; }; };",
2544 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002545 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002546 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002547 EXPECT_TRUE(
2548 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002549 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002550}
2551
2552TEST(Matcher, IsDefinition) {
2553 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002554 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002555 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2556 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2557
2558 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002559 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002560 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2561 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2562
2563 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002564 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002565 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2566 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2567}
2568
2569TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002570 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002571 ofClass(hasName("X")))));
2572
2573 EXPECT_TRUE(
2574 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2575 EXPECT_TRUE(
2576 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2577 Constructor));
2578 EXPECT_TRUE(
2579 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2580 Constructor));
2581}
2582
2583TEST(Matcher, VisitsTemplateInstantiations) {
2584 EXPECT_TRUE(matches(
2585 "class A { public: void x(); };"
2586 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002587 "void f() { B<A> b; b.y(); }",
2588 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002589
2590 EXPECT_TRUE(matches(
2591 "class A { public: void x(); };"
2592 "class C {"
2593 " public:"
2594 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2595 "};"
2596 "void f() {"
2597 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002598 "}",
2599 recordDecl(hasName("C"),
2600 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002601}
2602
Daniel Jasper1dad1832012-07-10 20:20:19 +00002603TEST(Matcher, HandlesNullQualTypes) {
2604 // FIXME: Add a Type matcher so we can replace uses of this
2605 // variable with Type(True())
2606 const TypeMatcher AnyType = anything();
2607
2608 // We don't really care whether this matcher succeeds; we're testing that
2609 // it completes without crashing.
2610 EXPECT_TRUE(matches(
2611 "struct A { };"
2612 "template <typename T>"
2613 "void f(T t) {"
2614 " T local_t(t /* this becomes a null QualType in the AST */);"
2615 "}"
2616 "void g() {"
2617 " f(0);"
2618 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002619 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002620 anyOf(
2621 TypeMatcher(hasDeclaration(anything())),
2622 pointsTo(AnyType),
2623 references(AnyType)
2624 // Other QualType matchers should go here.
2625 ))))));
2626}
2627
Manuel Klimek04616e42012-07-06 05:48:52 +00002628// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002629AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002630 // Make sure all special variables are used: node, match_finder,
2631 // bound_nodes_builder, and the parameter named 'AMatcher'.
2632 return AMatcher.matches(Node, Finder, Builder);
2633}
2634
2635TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002636 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002637
2638 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002639 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002640
2641 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002642 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002643
2644 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002645 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002646}
2647
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002648AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2649 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2650 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002651 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002652 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002653 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2654 ASTMatchFinder::BK_First);
2655}
2656
2657TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002658 DeclarationMatcher HasClassB =
2659 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002660
2661 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002662 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002663
2664 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002665 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002666
2667 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002668 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002669
2670 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002671 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002672
2673 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2674}
2675
2676TEST(For, FindsForLoops) {
2677 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2678 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002679 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2680 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002681 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002682}
2683
Daniel Jasper4e566c42012-07-12 08:50:38 +00002684TEST(For, ForLoopInternals) {
2685 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2686 forStmt(hasCondition(anything()))));
2687 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2688 forStmt(hasLoopInit(anything()))));
2689}
2690
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002691TEST(For, ForRangeLoopInternals) {
2692 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2693 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002694 EXPECT_TRUE(matches(
2695 "void f(){ int a[] {1, 2}; for (int i : a); }",
2696 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002697}
2698
Daniel Jasper4e566c42012-07-12 08:50:38 +00002699TEST(For, NegativeForLoopInternals) {
2700 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002701 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002702 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2703 forStmt(hasLoopInit(anything()))));
2704}
2705
Manuel Klimek04616e42012-07-06 05:48:52 +00002706TEST(For, ReportsNoFalsePositives) {
2707 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2708 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2709}
2710
2711TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002712 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2713 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2714 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002715}
2716
2717TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2718 // It's not a compound statement just because there's "{}" in the source
2719 // text. This is an AST search, not grep.
2720 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002721 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002722 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002723 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002724}
2725
Daniel Jasper4e566c42012-07-12 08:50:38 +00002726TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002727 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002728 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002729 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002730 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002731 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002732 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002733 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002734 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002735 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2736 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002737}
2738
2739TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2740 // The simplest case: every compound statement is in a function
2741 // definition, and the function body itself must be a compound
2742 // statement.
2743 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002744 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002745}
2746
2747TEST(HasAnySubstatement, IsNotRecursive) {
2748 // It's really "has any immediate substatement".
2749 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002750 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002751}
2752
2753TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2754 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002755 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002756}
2757
2758TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2759 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002760 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002761}
2762
2763TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2764 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002765 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002766 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002767 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002768}
2769
2770TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2771 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002772 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002773 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002774 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002775 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002776 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002777}
2778
2779TEST(StatementCountIs, WorksWithMultipleStatements) {
2780 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002781 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002782}
2783
2784TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2785 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002786 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002787 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002788 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002789 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002790 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002791 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002792 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002793}
2794
2795TEST(Member, WorksInSimplestCase) {
2796 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002797 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002798}
2799
2800TEST(Member, DoesNotMatchTheBaseExpression) {
2801 // Don't pick out the wrong part of the member expression, this should
2802 // be checking the member (name) only.
2803 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002804 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002805}
2806
2807TEST(Member, MatchesInMemberFunctionCall) {
2808 EXPECT_TRUE(matches("void f() {"
2809 " struct { void first() {}; } s;"
2810 " s.first();"
2811 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002812 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002813}
2814
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002815TEST(Member, MatchesMember) {
2816 EXPECT_TRUE(matches(
2817 "struct A { int i; }; void f() { A a; a.i = 2; }",
2818 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2819 EXPECT_TRUE(notMatches(
2820 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2821 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2822}
2823
Daniel Jasper639522c2013-02-25 12:02:08 +00002824TEST(Member, UnderstandsAccess) {
2825 EXPECT_TRUE(matches(
2826 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2827 EXPECT_TRUE(notMatches(
2828 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2829 EXPECT_TRUE(notMatches(
2830 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2831
2832 EXPECT_TRUE(notMatches(
2833 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2834 EXPECT_TRUE(notMatches(
2835 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2836 EXPECT_TRUE(matches(
2837 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2838
2839 EXPECT_TRUE(notMatches(
2840 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2841 EXPECT_TRUE(matches("class A { protected: int i; };",
2842 fieldDecl(isProtected(), hasName("i"))));
2843 EXPECT_TRUE(notMatches(
2844 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2845
2846 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2847 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2848 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2849 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2850}
2851
Dmitri Gribenko06963042012-08-18 00:29:27 +00002852TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002853 // Fails in C++11 mode
2854 EXPECT_TRUE(matchesConditionally(
2855 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2856 "class X { void *operator new(std::size_t); };",
2857 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002858
2859 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002860 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002861
Daniel Jasper5901e472012-10-01 13:40:41 +00002862 // Fails in C++11 mode
2863 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002864 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2865 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002866 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002867}
2868
Manuel Klimek04616e42012-07-06 05:48:52 +00002869TEST(HasObjectExpression, DoesNotMatchMember) {
2870 EXPECT_TRUE(notMatches(
2871 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002872 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002873}
2874
2875TEST(HasObjectExpression, MatchesBaseOfVariable) {
2876 EXPECT_TRUE(matches(
2877 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002878 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002879 EXPECT_TRUE(matches(
2880 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002881 memberExpr(hasObjectExpression(
2882 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002883}
2884
2885TEST(HasObjectExpression,
2886 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2887 EXPECT_TRUE(matches(
2888 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002889 memberExpr(hasObjectExpression(
2890 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002891 EXPECT_TRUE(matches(
2892 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002893 memberExpr(hasObjectExpression(
2894 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002895}
2896
2897TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002898 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2899 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2900 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2901 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002902}
2903
2904TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002905 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002906}
2907
2908TEST(IsConstQualified, MatchesConstInt) {
2909 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002910 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002911}
2912
2913TEST(IsConstQualified, MatchesConstPointer) {
2914 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002915 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002916}
2917
2918TEST(IsConstQualified, MatchesThroughTypedef) {
2919 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002920 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002921 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002922 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002923}
2924
2925TEST(IsConstQualified, DoesNotMatchInappropriately) {
2926 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002927 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002928 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002929 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002930}
2931
Sam Panzer80c13772012-08-16 16:58:10 +00002932TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002933 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2934 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2935 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2936 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002937}
2938TEST(CastExpression, MatchesImplicitCasts) {
2939 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002940 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002941 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002942 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002943}
2944
2945TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002946 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2947 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2948 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2949 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002950}
2951
Manuel Klimek04616e42012-07-06 05:48:52 +00002952TEST(ReinterpretCast, MatchesSimpleCase) {
2953 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002954 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002955}
2956
2957TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002958 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002959 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002960 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002961 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002962 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002963 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2964 "B b;"
2965 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002966 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002967}
2968
2969TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002970 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002971 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002972 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002973}
2974
2975TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002976 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002977 EXPECT_TRUE(
2978 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002979 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002980 EXPECT_TRUE(
2981 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002982 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002983}
2984
2985TEST(DynamicCast, MatchesSimpleCase) {
2986 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2987 "B b;"
2988 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002989 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002990}
2991
2992TEST(StaticCast, MatchesSimpleCase) {
2993 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002994 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002995}
2996
2997TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002998 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002999 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003000 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003001 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003002 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003003 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3004 "B b;"
3005 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003006 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003007}
3008
Daniel Jasper417f7762012-09-18 13:36:17 +00003009TEST(CStyleCast, MatchesSimpleCase) {
3010 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
3011}
3012
3013TEST(CStyleCast, DoesNotMatchOtherCasts) {
3014 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
3015 "char q, *r = const_cast<char*>(&q);"
3016 "void* s = reinterpret_cast<char*>(&s);"
3017 "struct B { virtual ~B() {} }; struct D : B {};"
3018 "B b;"
3019 "D* t = dynamic_cast<D*>(&b);",
3020 cStyleCastExpr()));
3021}
3022
Manuel Klimek04616e42012-07-06 05:48:52 +00003023TEST(HasDestinationType, MatchesSimpleCase) {
3024 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003025 staticCastExpr(hasDestinationType(
3026 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003027}
3028
Sam Panzer80c13772012-08-16 16:58:10 +00003029TEST(HasImplicitDestinationType, MatchesSimpleCase) {
3030 // This test creates an implicit const cast.
3031 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003032 implicitCastExpr(
3033 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003034 // This test creates an implicit array-to-pointer cast.
3035 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003036 implicitCastExpr(hasImplicitDestinationType(
3037 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003038}
3039
3040TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
3041 // This test creates an implicit cast from int to char.
3042 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003043 implicitCastExpr(hasImplicitDestinationType(
3044 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003045 // This test creates an implicit array-to-pointer cast.
3046 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003047 implicitCastExpr(hasImplicitDestinationType(
3048 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003049}
3050
3051TEST(ImplicitCast, MatchesSimpleCase) {
3052 // This test creates an implicit const cast.
3053 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003054 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003055 // This test creates an implicit cast from int to char.
3056 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003057 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003058 // This test creates an implicit array-to-pointer cast.
3059 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003060 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003061}
3062
3063TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003064 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00003065 // are present, and that it ignores explicit and paren casts.
3066
3067 // These two test cases have no casts.
3068 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003069 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003070 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003071 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003072
3073 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003074 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003075 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003076 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003077
3078 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003079 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003080}
3081
3082TEST(IgnoringImpCasts, MatchesImpCasts) {
3083 // This test checks that ignoringImpCasts matches when implicit casts are
3084 // present and its inner matcher alone does not match.
3085 // Note that this test creates an implicit const cast.
3086 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003087 varDecl(hasInitializer(ignoringImpCasts(
3088 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003089 // This test creates an implict cast from int to char.
3090 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003091 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003092 integerLiteral(equals(0)))))));
3093}
3094
3095TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3096 // These tests verify that ignoringImpCasts does not match if the inner
3097 // matcher does not match.
3098 // Note that the first test creates an implicit const cast.
3099 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003100 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003101 unless(anything()))))));
3102 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003103 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003104 unless(anything()))))));
3105
3106 // These tests verify that ignoringImplictCasts does not look through explicit
3107 // casts or parentheses.
3108 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003109 varDecl(hasInitializer(ignoringImpCasts(
3110 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003111 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003112 varDecl(hasInitializer(ignoringImpCasts(
3113 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003114 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003115 varDecl(hasInitializer(ignoringImpCasts(
3116 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003117 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003118 varDecl(hasInitializer(ignoringImpCasts(
3119 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003120}
3121
3122TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3123 // This test verifies that expressions that do not have implicit casts
3124 // still match the inner matcher.
3125 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003126 varDecl(hasInitializer(ignoringImpCasts(
3127 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003128}
3129
3130TEST(IgnoringParenCasts, MatchesParenCasts) {
3131 // This test checks that ignoringParenCasts matches when parentheses and/or
3132 // casts are present and its inner matcher alone does not match.
3133 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003134 varDecl(hasInitializer(ignoringParenCasts(
3135 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003136 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003137 varDecl(hasInitializer(ignoringParenCasts(
3138 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003139
3140 // This test creates an implict cast from int to char in addition to the
3141 // parentheses.
3142 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003143 varDecl(hasInitializer(ignoringParenCasts(
3144 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003145
3146 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003147 varDecl(hasInitializer(ignoringParenCasts(
3148 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003149 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003150 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003151 integerLiteral(equals(0)))))));
3152}
3153
3154TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3155 // This test verifies that expressions that do not have any casts still match.
3156 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003157 varDecl(hasInitializer(ignoringParenCasts(
3158 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003159}
3160
3161TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3162 // These tests verify that ignoringImpCasts does not match if the inner
3163 // matcher does not match.
3164 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003165 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003166 unless(anything()))))));
3167
3168 // This test creates an implicit cast from int to char in addition to the
3169 // parentheses.
3170 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003171 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003172 unless(anything()))))));
3173
3174 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003175 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003176 unless(anything()))))));
3177}
3178
3179TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3180 // This test checks that ignoringParenAndImpCasts matches when
3181 // parentheses and/or implicit casts are present and its inner matcher alone
3182 // does not match.
3183 // Note that this test creates an implicit const cast.
3184 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003185 varDecl(hasInitializer(ignoringParenImpCasts(
3186 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003187 // This test creates an implicit cast from int to char.
3188 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003189 varDecl(hasInitializer(ignoringParenImpCasts(
3190 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003191}
3192
3193TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3194 // This test verifies that expressions that do not have parentheses or
3195 // implicit casts still match.
3196 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003197 varDecl(hasInitializer(ignoringParenImpCasts(
3198 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003199 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003200 varDecl(hasInitializer(ignoringParenImpCasts(
3201 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003202}
3203
3204TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3205 // These tests verify that ignoringParenImpCasts does not match if
3206 // the inner matcher does not match.
3207 // This test creates an implicit cast.
3208 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003209 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003210 unless(anything()))))));
3211 // These tests verify that ignoringParenAndImplictCasts does not look
3212 // through explicit casts.
3213 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003214 varDecl(hasInitializer(ignoringParenImpCasts(
3215 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003216 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003217 varDecl(hasInitializer(ignoringParenImpCasts(
3218 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003219 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003220 varDecl(hasInitializer(ignoringParenImpCasts(
3221 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003222}
3223
Manuel Klimeke9235692012-07-25 10:02:02 +00003224TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003225 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3226 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003227 implicitCastExpr(
3228 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003229}
3230
Manuel Klimeke9235692012-07-25 10:02:02 +00003231TEST(HasSourceExpression, MatchesExplicitCasts) {
3232 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003233 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003234 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003235 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003236}
3237
Manuel Klimek04616e42012-07-06 05:48:52 +00003238TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003239 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003240}
3241
3242TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003243 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003244}
3245
3246TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003247 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003248}
3249
3250TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003251 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003252}
3253
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003254TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3255 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3256 "const Foo f = Foo();",
3257 varDecl(hasInitializer(exprWithCleanups()))));
3258 EXPECT_FALSE(matches("struct Foo { };"
3259 "const Foo f = Foo();",
3260 varDecl(hasInitializer(exprWithCleanups()))));
3261}
3262
Daniel Jasper1dad1832012-07-10 20:20:19 +00003263TEST(InitListExpression, MatchesInitListExpression) {
3264 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3265 initListExpr(hasType(asString("int [2]")))));
3266 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003267 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003268 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3269 "void f();"
3270 "S s[1] = { &f };",
3271 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003272 EXPECT_TRUE(
3273 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003274}
3275
3276TEST(UsingDeclaration, MatchesUsingDeclarations) {
3277 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3278 usingDecl()));
3279}
3280
3281TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3282 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3283 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3284}
3285
3286TEST(UsingDeclaration, MatchesSpecificTarget) {
3287 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3288 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003289 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003290 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3291 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003292 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003293}
3294
3295TEST(UsingDeclaration, ThroughUsingDeclaration) {
3296 EXPECT_TRUE(matches(
3297 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003298 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003299 EXPECT_TRUE(notMatches(
3300 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003301 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003302}
3303
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003304TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3305 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3306 usingDirectiveDecl()));
3307 EXPECT_FALSE(
3308 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3309}
3310
Sam Panzerd624bfb2012-08-16 17:20:59 +00003311TEST(SingleDecl, IsSingleDecl) {
3312 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003313 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003314 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3315 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3316 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3317 SingleDeclStmt));
3318}
3319
3320TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003321 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003322
3323 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003324 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003325 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003326 declStmt(containsDeclaration(0, MatchesInit),
3327 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003328 unsigned WrongIndex = 42;
3329 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003330 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003331 MatchesInit))));
3332}
3333
3334TEST(DeclCount, DeclCountIsCorrect) {
3335 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003336 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003337 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003338 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003339 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003340 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003341}
3342
Manuel Klimek04616e42012-07-06 05:48:52 +00003343TEST(While, MatchesWhileLoops) {
3344 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3345 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3346 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3347}
3348
3349TEST(Do, MatchesDoLoops) {
3350 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3351 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3352}
3353
3354TEST(Do, DoesNotMatchWhileLoops) {
3355 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3356}
3357
3358TEST(SwitchCase, MatchesCase) {
3359 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3360 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3361 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3362 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3363}
3364
Daniel Jasper87c3d362012-09-20 14:12:57 +00003365TEST(SwitchCase, MatchesSwitch) {
3366 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3367 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3368 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3369 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3370}
3371
Peter Collingbourne3154a102013-05-10 11:52:02 +00003372TEST(SwitchCase, MatchesEachCase) {
3373 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3374 switchStmt(forEachSwitchCase(caseStmt()))));
3375 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3376 switchStmt(forEachSwitchCase(caseStmt()))));
3377 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3378 switchStmt(forEachSwitchCase(caseStmt()))));
3379 EXPECT_TRUE(notMatches(
3380 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3381 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3382 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3383 switchStmt(forEachSwitchCase(
3384 caseStmt(hasCaseConstant(integerLiteral()))))));
3385 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3386 switchStmt(forEachSwitchCase(
3387 caseStmt(hasCaseConstant(integerLiteral()))))));
3388 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3389 switchStmt(forEachSwitchCase(
3390 caseStmt(hasCaseConstant(integerLiteral()))))));
3391 EXPECT_TRUE(matchAndVerifyResultTrue(
3392 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3393 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3394 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3395}
3396
Manuel Klimekba46fc02013-07-19 11:50:54 +00003397TEST(ForEachConstructorInitializer, MatchesInitializers) {
3398 EXPECT_TRUE(matches(
3399 "struct X { X() : i(42), j(42) {} int i, j; };",
3400 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3401}
3402
Daniel Jasper87c3d362012-09-20 14:12:57 +00003403TEST(ExceptionHandling, SimpleCases) {
3404 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3405 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3406 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3407 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3408 throwExpr()));
3409 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3410 throwExpr()));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003411 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
3412 catchStmt(isCatchAll())));
3413 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
3414 catchStmt(isCatchAll())));
Aaron Ballman39918462015-07-15 17:11:21 +00003415 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3416 varDecl(isExceptionVariable())));
3417 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3418 varDecl(isExceptionVariable())));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003419}
3420
Manuel Klimek04616e42012-07-06 05:48:52 +00003421TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3422 EXPECT_TRUE(notMatches(
3423 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003424 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003425 EXPECT_TRUE(notMatches(
3426 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003427 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003428}
3429
3430TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3431 EXPECT_TRUE(matches(
3432 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003433 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003434}
3435
3436TEST(ForEach, BindsOneNode) {
3437 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003438 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003439 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003440}
3441
3442TEST(ForEach, BindsMultipleNodes) {
3443 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003444 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003445 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003446}
3447
3448TEST(ForEach, BindsRecursiveCombinations) {
3449 EXPECT_TRUE(matchAndVerifyResultTrue(
3450 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003451 recordDecl(hasName("C"),
3452 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003453 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003454}
3455
3456TEST(ForEachDescendant, BindsOneNode) {
3457 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003458 recordDecl(hasName("C"),
3459 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003460 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003461}
3462
Daniel Jasper94a56852012-11-16 18:39:22 +00003463TEST(ForEachDescendant, NestedForEachDescendant) {
3464 DeclarationMatcher m = recordDecl(
3465 isDefinition(), decl().bind("x"), hasName("C"));
3466 EXPECT_TRUE(matchAndVerifyResultTrue(
3467 "class A { class B { class C {}; }; };",
3468 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3469 new VerifyIdIsBoundTo<Decl>("x", "C")));
3470
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003471 // Check that a partial match of 'm' that binds 'x' in the
3472 // first part of anyOf(m, anything()) will not overwrite the
3473 // binding created by the earlier binding in the hasDescendant.
3474 EXPECT_TRUE(matchAndVerifyResultTrue(
3475 "class A { class B { class C {}; }; };",
3476 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3477 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003478}
3479
Manuel Klimek04616e42012-07-06 05:48:52 +00003480TEST(ForEachDescendant, BindsMultipleNodes) {
3481 EXPECT_TRUE(matchAndVerifyResultTrue(
3482 "class C { class D { int x; int y; }; "
3483 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003484 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003485 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003486}
3487
3488TEST(ForEachDescendant, BindsRecursiveCombinations) {
3489 EXPECT_TRUE(matchAndVerifyResultTrue(
3490 "class C { class D { "
3491 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003492 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3493 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003494 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003495}
3496
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003497TEST(ForEachDescendant, BindsCombinations) {
3498 EXPECT_TRUE(matchAndVerifyResultTrue(
3499 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3500 "(true) {} }",
3501 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3502 forEachDescendant(whileStmt().bind("while"))),
3503 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3504}
3505
3506TEST(Has, DoesNotDeleteBindings) {
3507 EXPECT_TRUE(matchAndVerifyResultTrue(
3508 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3509 new VerifyIdIsBoundTo<Decl>("x", 1)));
3510}
3511
3512TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3513 // Those matchers cover all the cases where an inner matcher is called
3514 // and there is not a 1:1 relationship between the match of the outer
3515 // matcher and the match of the inner matcher.
3516 // The pattern to look for is:
3517 // ... return InnerMatcher.matches(...); ...
3518 // In which case no special handling is needed.
3519 //
3520 // On the other hand, if there are multiple alternative matches
3521 // (for example forEach*) or matches might be discarded (for example has*)
3522 // the implementation must make sure that the discarded matches do not
3523 // affect the bindings.
3524 // When new such matchers are added, add a test here that:
3525 // - matches a simple node, and binds it as the first thing in the matcher:
3526 // recordDecl(decl().bind("x"), hasName("X")))
3527 // - uses the matcher under test afterwards in a way that not the first
3528 // alternative is matched; for anyOf, that means the first branch
3529 // would need to return false; for hasAncestor, it means that not
3530 // the direct parent matches the inner matcher.
3531
3532 EXPECT_TRUE(matchAndVerifyResultTrue(
3533 "class X { int y; };",
3534 recordDecl(
3535 recordDecl().bind("x"), hasName("::X"),
3536 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3537 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3538 EXPECT_TRUE(matchAndVerifyResultTrue(
3539 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3540 anyOf(unless(anything()), anything())),
3541 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3542 EXPECT_TRUE(matchAndVerifyResultTrue(
3543 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3544 classTemplateSpecializationDecl(
3545 decl().bind("x"),
3546 hasAnyTemplateArgument(refersToType(asString("int")))),
3547 new VerifyIdIsBoundTo<Decl>("x", 1)));
3548 EXPECT_TRUE(matchAndVerifyResultTrue(
3549 "class X { void f(); void g(); };",
3550 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3551 new VerifyIdIsBoundTo<Decl>("x", 1)));
3552 EXPECT_TRUE(matchAndVerifyResultTrue(
3553 "class X { X() : a(1), b(2) {} double a; int b; };",
3554 recordDecl(decl().bind("x"),
3555 has(constructorDecl(
3556 hasAnyConstructorInitializer(forField(hasName("b")))))),
3557 new VerifyIdIsBoundTo<Decl>("x", 1)));
3558 EXPECT_TRUE(matchAndVerifyResultTrue(
3559 "void x(int, int) { x(0, 42); }",
3560 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3561 new VerifyIdIsBoundTo<Expr>("x", 1)));
3562 EXPECT_TRUE(matchAndVerifyResultTrue(
3563 "void x(int, int y) {}",
3564 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3565 new VerifyIdIsBoundTo<Decl>("x", 1)));
3566 EXPECT_TRUE(matchAndVerifyResultTrue(
3567 "void x() { return; if (true) {} }",
3568 functionDecl(decl().bind("x"),
3569 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3570 new VerifyIdIsBoundTo<Decl>("x", 1)));
3571 EXPECT_TRUE(matchAndVerifyResultTrue(
3572 "namespace X { void b(int); void b(); }"
3573 "using X::b;",
3574 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3575 functionDecl(parameterCountIs(1))))),
3576 new VerifyIdIsBoundTo<Decl>("x", 1)));
3577 EXPECT_TRUE(matchAndVerifyResultTrue(
3578 "class A{}; class B{}; class C : B, A {};",
3579 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3580 new VerifyIdIsBoundTo<Decl>("x", 1)));
3581 EXPECT_TRUE(matchAndVerifyResultTrue(
3582 "class A{}; typedef A B; typedef A C; typedef A D;"
3583 "class E : A {};",
3584 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3585 new VerifyIdIsBoundTo<Decl>("x", 1)));
3586 EXPECT_TRUE(matchAndVerifyResultTrue(
3587 "class A { class B { void f() {} }; };",
3588 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3589 new VerifyIdIsBoundTo<Decl>("x", 1)));
3590 EXPECT_TRUE(matchAndVerifyResultTrue(
3591 "template <typename T> struct A { struct B {"
3592 " void f() { if(true) {} }"
3593 "}; };"
3594 "void t() { A<int>::B b; b.f(); }",
3595 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3596 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3597 EXPECT_TRUE(matchAndVerifyResultTrue(
3598 "class A {};",
3599 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3600 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003601 EXPECT_TRUE(matchAndVerifyResultTrue(
3602 "class A { A() : s(), i(42) {} const char *s; int i; };",
3603 constructorDecl(hasName("::A::A"), decl().bind("x"),
3604 forEachConstructorInitializer(forField(hasName("i")))),
3605 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003606}
3607
Daniel Jasper33806cd2012-11-11 22:14:55 +00003608TEST(ForEachDescendant, BindsCorrectNodes) {
3609 EXPECT_TRUE(matchAndVerifyResultTrue(
3610 "class C { void f(); int i; };",
3611 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3612 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3613 EXPECT_TRUE(matchAndVerifyResultTrue(
3614 "class C { void f() {} int i; };",
3615 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3616 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3617}
3618
Manuel Klimekabf43712013-02-04 10:59:20 +00003619TEST(FindAll, BindsNodeOnMatch) {
3620 EXPECT_TRUE(matchAndVerifyResultTrue(
3621 "class A {};",
3622 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3623 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3624}
3625
3626TEST(FindAll, BindsDescendantNodeOnMatch) {
3627 EXPECT_TRUE(matchAndVerifyResultTrue(
3628 "class A { int a; int b; };",
3629 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3630 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3631}
3632
3633TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3634 EXPECT_TRUE(matchAndVerifyResultTrue(
3635 "class A { int a; int b; };",
3636 recordDecl(hasName("::A"),
3637 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3638 fieldDecl().bind("v"))))),
3639 new VerifyIdIsBoundTo<Decl>("v", 3)));
3640
3641 EXPECT_TRUE(matchAndVerifyResultTrue(
3642 "class A { class B {}; class C {}; };",
3643 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3644 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3645}
3646
Manuel Klimek88b95872013-02-04 09:42:38 +00003647TEST(EachOf, TriggersForEachMatch) {
3648 EXPECT_TRUE(matchAndVerifyResultTrue(
3649 "class A { int a; int b; };",
3650 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3651 has(fieldDecl(hasName("b")).bind("v")))),
3652 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3653}
3654
3655TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3656 EXPECT_TRUE(matchAndVerifyResultTrue(
3657 "class A { int a; int c; };",
3658 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3659 has(fieldDecl(hasName("b")).bind("v")))),
3660 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3661 EXPECT_TRUE(matchAndVerifyResultTrue(
3662 "class A { int c; int b; };",
3663 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3664 has(fieldDecl(hasName("b")).bind("v")))),
3665 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3666 EXPECT_TRUE(notMatches(
3667 "class A { int c; int d; };",
3668 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3669 has(fieldDecl(hasName("b")).bind("v"))))));
3670}
Manuel Klimek04616e42012-07-06 05:48:52 +00003671
3672TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3673 // Make sure that we can both match the class by name (::X) and by the type
3674 // the template was instantiated with (via a field).
3675
3676 EXPECT_TRUE(matches(
3677 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003678 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003679
3680 EXPECT_TRUE(matches(
3681 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003682 recordDecl(isTemplateInstantiation(), hasDescendant(
3683 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003684}
3685
3686TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3687 EXPECT_TRUE(matches(
3688 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003689 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003690 isTemplateInstantiation())));
3691}
3692
3693TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3694 EXPECT_TRUE(matches(
3695 "template <typename T> class X { T t; }; class A {};"
3696 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003697 recordDecl(isTemplateInstantiation(), hasDescendant(
3698 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003699}
3700
3701TEST(IsTemplateInstantiation,
3702 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3703 EXPECT_TRUE(matches(
3704 "template <typename T> class X {};"
3705 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003706 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003707}
3708
3709TEST(IsTemplateInstantiation,
3710 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3711 EXPECT_TRUE(matches(
3712 "class A {};"
3713 "class X {"
3714 " template <typename U> class Y { U u; };"
3715 " Y<A> y;"
3716 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003717 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003718}
3719
3720TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3721 // FIXME: Figure out whether this makes sense. It doesn't affect the
3722 // normal use case as long as the uppermost instantiation always is marked
3723 // as template instantiation, but it might be confusing as a predicate.
3724 EXPECT_TRUE(matches(
3725 "class A {};"
3726 "template <typename T> class X {"
3727 " template <typename U> class Y { U u; };"
3728 " Y<T> y;"
3729 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003730 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003731}
3732
3733TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3734 EXPECT_TRUE(notMatches(
3735 "template <typename T> class X {}; class A {};"
3736 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003737 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003738}
3739
3740TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3741 EXPECT_TRUE(notMatches(
3742 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003743 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003744}
3745
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003746TEST(IsInstantiated, MatchesInstantiation) {
3747 EXPECT_TRUE(
3748 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3749 recordDecl(isInstantiated())));
3750}
3751
3752TEST(IsInstantiated, NotMatchesDefinition) {
3753 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3754 recordDecl(isInstantiated())));
3755}
3756
3757TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3758 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3759 "class Y { A<int> a; }; Y y;",
3760 declStmt(isInTemplateInstantiation())));
3761}
3762
3763TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3764 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3765 declStmt(isInTemplateInstantiation())));
3766}
3767
3768TEST(IsInstantiated, MatchesFunctionInstantiation) {
3769 EXPECT_TRUE(
3770 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3771 functionDecl(isInstantiated())));
3772}
3773
3774TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3775 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3776 varDecl(isInstantiated())));
3777}
3778
3779TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3780 EXPECT_TRUE(
3781 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3782 declStmt(isInTemplateInstantiation())));
3783}
3784
3785TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3786 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3787 declStmt(isInTemplateInstantiation())));
3788}
3789
3790TEST(IsInTemplateInstantiation, Sharing) {
3791 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3792 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3793 // and makes the matcher behave in non-obvious ways.
3794 EXPECT_TRUE(notMatches(
3795 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3796 Matcher));
3797 EXPECT_TRUE(matches(
3798 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3799 Matcher));
3800}
3801
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003802TEST(IsExplicitTemplateSpecialization,
3803 DoesNotMatchPrimaryTemplate) {
3804 EXPECT_TRUE(notMatches(
3805 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003806 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003807 EXPECT_TRUE(notMatches(
3808 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003809 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003810}
3811
3812TEST(IsExplicitTemplateSpecialization,
3813 DoesNotMatchExplicitTemplateInstantiations) {
3814 EXPECT_TRUE(notMatches(
3815 "template <typename T> class X {};"
3816 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003817 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003818 EXPECT_TRUE(notMatches(
3819 "template <typename T> void f(T t) {}"
3820 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003821 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003822}
3823
3824TEST(IsExplicitTemplateSpecialization,
3825 DoesNotMatchImplicitTemplateInstantiations) {
3826 EXPECT_TRUE(notMatches(
3827 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003828 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003829 EXPECT_TRUE(notMatches(
3830 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003831 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003832}
3833
3834TEST(IsExplicitTemplateSpecialization,
3835 MatchesExplicitTemplateSpecializations) {
3836 EXPECT_TRUE(matches(
3837 "template <typename T> class X {};"
3838 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003839 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003840 EXPECT_TRUE(matches(
3841 "template <typename T> void f(T t) {}"
3842 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003843 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003844}
3845
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003846TEST(HasAncenstor, MatchesDeclarationAncestors) {
3847 EXPECT_TRUE(matches(
3848 "class A { class B { class C {}; }; };",
3849 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3850}
3851
3852TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3853 EXPECT_TRUE(notMatches(
3854 "class A { class B { class C {}; }; };",
3855 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3856}
3857
3858TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3859 EXPECT_TRUE(matches(
3860 "class A { class B { void f() { C c; } class C {}; }; };",
3861 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3862 hasAncestor(recordDecl(hasName("A"))))))));
3863}
3864
3865TEST(HasAncenstor, MatchesStatementAncestors) {
3866 EXPECT_TRUE(matches(
3867 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003868 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003869}
3870
3871TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3872 EXPECT_TRUE(matches(
3873 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003874 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003875}
3876
3877TEST(HasAncestor, BindsRecursiveCombinations) {
3878 EXPECT_TRUE(matchAndVerifyResultTrue(
3879 "class C { class D { class E { class F { int y; }; }; }; };",
3880 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003881 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003882}
3883
3884TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3885 EXPECT_TRUE(matchAndVerifyResultTrue(
3886 "class C { class D { class E { class F { int y; }; }; }; };",
3887 fieldDecl(hasAncestor(
3888 decl(
3889 hasDescendant(recordDecl(isDefinition(),
3890 hasAncestor(recordDecl())))
3891 ).bind("d")
3892 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003893 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003894}
3895
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003896TEST(HasAncestor, MatchesClosestAncestor) {
3897 EXPECT_TRUE(matchAndVerifyResultTrue(
3898 "template <typename T> struct C {"
3899 " void f(int) {"
3900 " struct I { void g(T) { int x; } } i; i.g(42);"
3901 " }"
3902 "};"
3903 "template struct C<int>;",
3904 varDecl(hasName("x"),
3905 hasAncestor(functionDecl(hasParameter(
3906 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3907 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3908}
3909
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003910TEST(HasAncestor, MatchesInTemplateInstantiations) {
3911 EXPECT_TRUE(matches(
3912 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3913 "A<int>::B::C a;",
3914 fieldDecl(hasType(asString("int")),
3915 hasAncestor(recordDecl(hasName("A"))))));
3916}
3917
3918TEST(HasAncestor, MatchesInImplicitCode) {
3919 EXPECT_TRUE(matches(
3920 "struct X {}; struct A { A() {} X x; };",
3921 constructorDecl(
3922 hasAnyConstructorInitializer(withInitializer(expr(
3923 hasAncestor(recordDecl(hasName("A")))))))));
3924}
3925
Daniel Jasper632aea92012-10-22 16:26:51 +00003926TEST(HasParent, MatchesOnlyParent) {
3927 EXPECT_TRUE(matches(
3928 "void f() { if (true) { int x = 42; } }",
3929 compoundStmt(hasParent(ifStmt()))));
3930 EXPECT_TRUE(notMatches(
3931 "void f() { for (;;) { int x = 42; } }",
3932 compoundStmt(hasParent(ifStmt()))));
3933 EXPECT_TRUE(notMatches(
3934 "void f() { if (true) for (;;) { int x = 42; } }",
3935 compoundStmt(hasParent(ifStmt()))));
3936}
3937
Manuel Klimekc844a462012-12-06 14:42:48 +00003938TEST(HasAncestor, MatchesAllAncestors) {
3939 EXPECT_TRUE(matches(
3940 "template <typename T> struct C { static void f() { 42; } };"
3941 "void t() { C<int>::f(); }",
3942 integerLiteral(
3943 equals(42),
3944 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3945 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3946}
3947
3948TEST(HasParent, MatchesAllParents) {
3949 EXPECT_TRUE(matches(
3950 "template <typename T> struct C { static void f() { 42; } };"
3951 "void t() { C<int>::f(); }",
3952 integerLiteral(
3953 equals(42),
3954 hasParent(compoundStmt(hasParent(functionDecl(
3955 hasParent(recordDecl(isTemplateInstantiation())))))))));
3956 EXPECT_TRUE(matches(
3957 "template <typename T> struct C { static void f() { 42; } };"
3958 "void t() { C<int>::f(); }",
3959 integerLiteral(
3960 equals(42),
3961 hasParent(compoundStmt(hasParent(functionDecl(
3962 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3963 EXPECT_TRUE(matches(
3964 "template <typename T> struct C { static void f() { 42; } };"
3965 "void t() { C<int>::f(); }",
3966 integerLiteral(equals(42),
3967 hasParent(compoundStmt(allOf(
3968 hasParent(functionDecl(
3969 hasParent(recordDecl(isTemplateInstantiation())))),
3970 hasParent(functionDecl(hasParent(recordDecl(
3971 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003972 EXPECT_TRUE(
3973 notMatches("template <typename T> struct C { static void f() {} };"
3974 "void t() { C<int>::f(); }",
3975 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003976}
3977
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003978TEST(HasParent, NoDuplicateParents) {
3979 class HasDuplicateParents : public BoundNodesCallback {
3980 public:
3981 bool run(const BoundNodes *Nodes) override { return false; }
3982 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3983 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3984 std::set<const void *> Parents;
3985 for (const auto &Parent : Context->getParents(*Node)) {
3986 if (!Parents.insert(Parent.getMemoizationData()).second) {
3987 return true;
3988 }
3989 }
3990 return false;
3991 }
3992 };
3993 EXPECT_FALSE(matchAndVerifyResultTrue(
3994 "template <typename T> int Foo() { return 1 + 2; }\n"
3995 "int x = Foo<int>() + Foo<unsigned>();",
3996 stmt().bind("node"), new HasDuplicateParents()));
3997}
3998
Daniel Jasper516b02e2012-10-17 08:52:59 +00003999TEST(TypeMatching, MatchesTypes) {
4000 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
4001}
4002
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004003TEST(TypeMatching, MatchesVoid) {
4004 EXPECT_TRUE(
4005 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
4006}
4007
Daniel Jasper516b02e2012-10-17 08:52:59 +00004008TEST(TypeMatching, MatchesArrayTypes) {
4009 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
4010 EXPECT_TRUE(matches("int a[42];", arrayType()));
4011 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
4012
4013 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
4014 arrayType(hasElementType(builtinType()))));
4015
4016 EXPECT_TRUE(matches(
4017 "int const a[] = { 2, 3 };",
4018 qualType(arrayType(hasElementType(builtinType())))));
4019 EXPECT_TRUE(matches(
4020 "int const a[] = { 2, 3 };",
4021 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4022 EXPECT_TRUE(matches(
4023 "typedef const int T; T x[] = { 1, 2 };",
4024 qualType(isConstQualified(), arrayType())));
4025
4026 EXPECT_TRUE(notMatches(
4027 "int a[] = { 2, 3 };",
4028 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4029 EXPECT_TRUE(notMatches(
4030 "int a[] = { 2, 3 };",
4031 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
4032 EXPECT_TRUE(notMatches(
4033 "int const a[] = { 2, 3 };",
4034 qualType(arrayType(hasElementType(builtinType())),
4035 unless(isConstQualified()))));
4036
4037 EXPECT_TRUE(matches("int a[2];",
4038 constantArrayType(hasElementType(builtinType()))));
4039 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
4040}
4041
4042TEST(TypeMatching, MatchesComplexTypes) {
4043 EXPECT_TRUE(matches("_Complex float f;", complexType()));
4044 EXPECT_TRUE(matches(
4045 "_Complex float f;",
4046 complexType(hasElementType(builtinType()))));
4047 EXPECT_TRUE(notMatches(
4048 "_Complex float f;",
4049 complexType(hasElementType(isInteger()))));
4050}
4051
4052TEST(TypeMatching, MatchesConstantArrayTypes) {
4053 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
4054 EXPECT_TRUE(notMatches(
4055 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
4056 constantArrayType(hasElementType(builtinType()))));
4057
4058 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
4059 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
4060 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
4061}
4062
4063TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
4064 EXPECT_TRUE(matches(
4065 "template <typename T, int Size> class array { T data[Size]; };",
4066 dependentSizedArrayType()));
4067 EXPECT_TRUE(notMatches(
4068 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
4069 dependentSizedArrayType()));
4070}
4071
4072TEST(TypeMatching, MatchesIncompleteArrayType) {
4073 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
4074 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
4075
4076 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
4077 incompleteArrayType()));
4078}
4079
4080TEST(TypeMatching, MatchesVariableArrayType) {
4081 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
4082 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4083
4084 EXPECT_TRUE(matches(
4085 "void f(int b) { int a[b]; }",
4086 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4087 varDecl(hasName("b")))))))));
4088}
4089
4090TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00004091 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4092 llvm::Triple::Win32) {
4093 // FIXME: Make this work for MSVC.
4094 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004095
David Majnemer197e2102014-03-05 06:32:38 +00004096 EXPECT_TRUE(matches("_Atomic(int) i;",
4097 atomicType(hasValueType(isInteger()))));
4098 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4099 atomicType(hasValueType(isInteger()))));
4100 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004101}
4102
4103TEST(TypeMatching, MatchesAutoTypes) {
4104 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4105 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4106 autoType()));
4107
Richard Smith061f1e22013-04-30 21:23:01 +00004108 // FIXME: Matching against the type-as-written can't work here, because the
4109 // type as written was not deduced.
4110 //EXPECT_TRUE(matches("auto a = 1;",
4111 // autoType(hasDeducedType(isInteger()))));
4112 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4113 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004114}
4115
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004116TEST(TypeMatching, MatchesFunctionTypes) {
4117 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4118 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4119}
4120
Edwin Vaneec074802013-04-01 18:33:34 +00004121TEST(TypeMatching, MatchesParenType) {
4122 EXPECT_TRUE(
4123 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4124 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4125
4126 EXPECT_TRUE(matches(
4127 "int (*ptr_to_func)(int);",
4128 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4129 EXPECT_TRUE(notMatches(
4130 "int (*ptr_to_array)[4];",
4131 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4132}
4133
Daniel Jasper516b02e2012-10-17 08:52:59 +00004134TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004135 // FIXME: Reactive when these tests can be more specific (not matching
4136 // implicit code on certain platforms), likely when we have hasDescendant for
4137 // Types/TypeLocs.
4138 //EXPECT_TRUE(matchAndVerifyResultTrue(
4139 // "int* a;",
4140 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4141 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4142 //EXPECT_TRUE(matchAndVerifyResultTrue(
4143 // "int* a;",
4144 // pointerTypeLoc().bind("loc"),
4145 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004146 EXPECT_TRUE(matches(
4147 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004148 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004149 EXPECT_TRUE(matches(
4150 "int** a;",
4151 loc(pointerType(pointee(pointerType())))));
4152 EXPECT_TRUE(matches(
4153 "int* b; int* * const a = &b;",
4154 loc(qualType(isConstQualified(), pointerType()))));
4155
4156 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004157 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4158 hasType(blockPointerType()))));
4159 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4160 hasType(memberPointerType()))));
4161 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4162 hasType(pointerType()))));
4163 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4164 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004165 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4166 hasType(lValueReferenceType()))));
4167 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4168 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004169
Daniel Jasper7943eb52012-10-17 13:35:36 +00004170 Fragment = "int *ptr;";
4171 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4172 hasType(blockPointerType()))));
4173 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4174 hasType(memberPointerType()))));
4175 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4176 hasType(pointerType()))));
4177 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4178 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004179
Daniel Jasper7943eb52012-10-17 13:35:36 +00004180 Fragment = "int a; int &ref = a;";
4181 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4182 hasType(blockPointerType()))));
4183 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4184 hasType(memberPointerType()))));
4185 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4186 hasType(pointerType()))));
4187 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4188 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004189 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4190 hasType(lValueReferenceType()))));
4191 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4192 hasType(rValueReferenceType()))));
4193
4194 Fragment = "int &&ref = 2;";
4195 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4196 hasType(blockPointerType()))));
4197 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4198 hasType(memberPointerType()))));
4199 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4200 hasType(pointerType()))));
4201 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4202 hasType(referenceType()))));
4203 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4204 hasType(lValueReferenceType()))));
4205 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4206 hasType(rValueReferenceType()))));
4207}
4208
4209TEST(TypeMatching, AutoRefTypes) {
4210 std::string Fragment = "auto a = 1;"
4211 "auto b = a;"
4212 "auto &c = a;"
4213 "auto &&d = c;"
4214 "auto &&e = 2;";
4215 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4216 hasType(referenceType()))));
4217 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4218 hasType(referenceType()))));
4219 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4220 hasType(referenceType()))));
4221 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4222 hasType(lValueReferenceType()))));
4223 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4224 hasType(rValueReferenceType()))));
4225 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4226 hasType(referenceType()))));
4227 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4228 hasType(lValueReferenceType()))));
4229 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4230 hasType(rValueReferenceType()))));
4231 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4232 hasType(referenceType()))));
4233 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4234 hasType(lValueReferenceType()))));
4235 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4236 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004237}
4238
4239TEST(TypeMatching, PointeeTypes) {
4240 EXPECT_TRUE(matches("int b; int &a = b;",
4241 referenceType(pointee(builtinType()))));
4242 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4243
4244 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004245 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004246
4247 EXPECT_TRUE(matches(
4248 "int const *A;",
4249 pointerType(pointee(isConstQualified(), builtinType()))));
4250 EXPECT_TRUE(notMatches(
4251 "int *A;",
4252 pointerType(pointee(isConstQualified(), builtinType()))));
4253}
4254
4255TEST(TypeMatching, MatchesPointersToConstTypes) {
4256 EXPECT_TRUE(matches("int b; int * const a = &b;",
4257 loc(pointerType())));
4258 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004259 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004260 EXPECT_TRUE(matches(
4261 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004262 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004263 EXPECT_TRUE(matches(
4264 "int b; const int * a = &b;",
4265 pointerType(pointee(builtinType()))));
4266}
4267
4268TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004269 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4270 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004271}
4272
Edwin Vanef901b712013-02-25 14:49:29 +00004273TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004274 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004275 templateSpecializationType()));
4276}
4277
Edwin Vaneb6eae142013-02-25 20:43:32 +00004278TEST(TypeMatching, MatchesRecordType) {
4279 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004280 EXPECT_TRUE(matches("struct S{}; S s;",
4281 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4282 EXPECT_TRUE(notMatches("int i;",
4283 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004284}
4285
4286TEST(TypeMatching, MatchesElaboratedType) {
4287 EXPECT_TRUE(matches(
4288 "namespace N {"
4289 " namespace M {"
4290 " class D {};"
4291 " }"
4292 "}"
4293 "N::M::D d;", elaboratedType()));
4294 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4295 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4296}
4297
4298TEST(ElaboratedTypeNarrowing, hasQualifier) {
4299 EXPECT_TRUE(matches(
4300 "namespace N {"
4301 " namespace M {"
4302 " class D {};"
4303 " }"
4304 "}"
4305 "N::M::D d;",
4306 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4307 EXPECT_TRUE(notMatches(
4308 "namespace M {"
4309 " class D {};"
4310 "}"
4311 "M::D d;",
4312 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004313 EXPECT_TRUE(notMatches(
4314 "struct D {"
4315 "} d;",
4316 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004317}
4318
4319TEST(ElaboratedTypeNarrowing, namesType) {
4320 EXPECT_TRUE(matches(
4321 "namespace N {"
4322 " namespace M {"
4323 " class D {};"
4324 " }"
4325 "}"
4326 "N::M::D d;",
4327 elaboratedType(elaboratedType(namesType(recordType(
4328 hasDeclaration(namedDecl(hasName("D")))))))));
4329 EXPECT_TRUE(notMatches(
4330 "namespace M {"
4331 " class D {};"
4332 "}"
4333 "M::D d;",
4334 elaboratedType(elaboratedType(namesType(typedefType())))));
4335}
4336
Samuel Benzaquenf8ec4542015-08-26 16:15:59 +00004337TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
4338 const std::string code = "template <typename T>"
4339 "int F() {"
4340 " return 1 + T();"
4341 "}"
4342 "int i = F<int>();";
4343 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
4344 expr(hasType(substTemplateTypeParmType()))))));
4345 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
4346 expr(hasType(substTemplateTypeParmType()))))));
4347}
4348
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004349TEST(NNS, MatchesNestedNameSpecifiers) {
4350 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4351 nestedNameSpecifier()));
4352 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4353 nestedNameSpecifier()));
4354 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4355 nestedNameSpecifier()));
4356
4357 EXPECT_TRUE(matches(
4358 "struct A { static void f() {} }; void g() { A::f(); }",
4359 nestedNameSpecifier()));
4360 EXPECT_TRUE(notMatches(
4361 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4362 nestedNameSpecifier()));
4363}
4364
Daniel Jasper87c3d362012-09-20 14:12:57 +00004365TEST(NullStatement, SimpleCases) {
4366 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4367 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4368}
4369
Aaron Ballman11825f22015-08-18 19:55:20 +00004370TEST(NS, Anonymous) {
4371 EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
4372 EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
4373}
4374
Aaron Ballman6c79f352015-08-28 19:39:21 +00004375TEST(NS, Alias) {
4376 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
4377 namespaceAliasDecl(hasName("alias"))));
4378}
4379
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004380TEST(NNS, MatchesTypes) {
4381 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4382 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4383 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4384 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4385 Matcher));
4386 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4387}
4388
4389TEST(NNS, MatchesNamespaceDecls) {
4390 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4391 specifiesNamespace(hasName("ns")));
4392 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4393 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4394 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4395}
4396
4397TEST(NNS, BindsNestedNameSpecifiers) {
4398 EXPECT_TRUE(matchAndVerifyResultTrue(
4399 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4400 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4401 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4402}
4403
4404TEST(NNS, BindsNestedNameSpecifierLocs) {
4405 EXPECT_TRUE(matchAndVerifyResultTrue(
4406 "namespace ns { struct B {}; } ns::B b;",
4407 loc(nestedNameSpecifier()).bind("loc"),
4408 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4409}
4410
4411TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4412 EXPECT_TRUE(matches(
4413 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4414 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4415 EXPECT_TRUE(matches(
4416 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004417 nestedNameSpecifierLoc(hasPrefix(
4418 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004419}
4420
Daniel Jasper6fc34332012-10-30 15:42:00 +00004421TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4422 std::string Fragment =
4423 "namespace a { struct A { struct B { struct C {}; }; }; };"
4424 "void f() { a::A::B::C c; }";
4425 EXPECT_TRUE(matches(
4426 Fragment,
4427 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4428 hasDescendant(nestedNameSpecifier(
4429 specifiesNamespace(hasName("a")))))));
4430 EXPECT_TRUE(notMatches(
4431 Fragment,
4432 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4433 has(nestedNameSpecifier(
4434 specifiesNamespace(hasName("a")))))));
4435 EXPECT_TRUE(matches(
4436 Fragment,
4437 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4438 has(nestedNameSpecifier(
4439 specifiesNamespace(hasName("a")))))));
4440
4441 // Not really useful because a NestedNameSpecifier can af at most one child,
4442 // but to complete the interface.
4443 EXPECT_TRUE(matchAndVerifyResultTrue(
4444 Fragment,
4445 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4446 forEach(nestedNameSpecifier().bind("x"))),
4447 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4448}
4449
4450TEST(NNS, NestedNameSpecifiersAsDescendants) {
4451 std::string Fragment =
4452 "namespace a { struct A { struct B { struct C {}; }; }; };"
4453 "void f() { a::A::B::C c; }";
4454 EXPECT_TRUE(matches(
4455 Fragment,
4456 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4457 asString("struct a::A")))))));
4458 EXPECT_TRUE(matchAndVerifyResultTrue(
4459 Fragment,
4460 functionDecl(hasName("f"),
4461 forEachDescendant(nestedNameSpecifier().bind("x"))),
4462 // Nested names: a, a::A and a::A::B.
4463 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4464}
4465
4466TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4467 std::string Fragment =
4468 "namespace a { struct A { struct B { struct C {}; }; }; };"
4469 "void f() { a::A::B::C c; }";
4470 EXPECT_TRUE(matches(
4471 Fragment,
4472 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4473 hasDescendant(loc(nestedNameSpecifier(
4474 specifiesNamespace(hasName("a"))))))));
4475 EXPECT_TRUE(notMatches(
4476 Fragment,
4477 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4478 has(loc(nestedNameSpecifier(
4479 specifiesNamespace(hasName("a"))))))));
4480 EXPECT_TRUE(matches(
4481 Fragment,
4482 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4483 has(loc(nestedNameSpecifier(
4484 specifiesNamespace(hasName("a"))))))));
4485
4486 EXPECT_TRUE(matchAndVerifyResultTrue(
4487 Fragment,
4488 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4489 forEach(nestedNameSpecifierLoc().bind("x"))),
4490 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4491}
4492
4493TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4494 std::string Fragment =
4495 "namespace a { struct A { struct B { struct C {}; }; }; };"
4496 "void f() { a::A::B::C c; }";
4497 EXPECT_TRUE(matches(
4498 Fragment,
4499 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4500 asString("struct a::A"))))))));
4501 EXPECT_TRUE(matchAndVerifyResultTrue(
4502 Fragment,
4503 functionDecl(hasName("f"),
4504 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4505 // Nested names: a, a::A and a::A::B.
4506 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4507}
4508
Manuel Klimek191c0932013-02-01 13:41:35 +00004509template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004510public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004511 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4512 StringRef InnerId)
4513 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004514 }
4515
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004516 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004517
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004518 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004519 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004520 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4521 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004522 }
4523private:
4524 std::string Id;
4525 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004526 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004527};
4528
4529TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004530 EXPECT_TRUE(matchAndVerifyResultTrue(
4531 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4532 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004533 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4534 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004535 EXPECT_TRUE(matchAndVerifyResultFalse(
4536 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4537 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004538 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4539 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004540}
4541
4542TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004543 EXPECT_TRUE(matchAndVerifyResultTrue(
4544 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004545 new VerifyMatchOnNode<clang::Stmt>(
4546 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004547 EXPECT_TRUE(matchAndVerifyResultFalse(
4548 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004549 new VerifyMatchOnNode<clang::Stmt>(
4550 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004551}
4552
4553TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4554 EXPECT_TRUE(matchAndVerifyResultTrue(
4555 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4556 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004557 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004558 EXPECT_TRUE(matchAndVerifyResultFalse(
4559 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4560 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004561 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004562}
4563
Manuel Klimekbee08572013-02-07 12:42:10 +00004564template <typename T>
4565class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4566public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004567 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004568
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004569 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004570 const T *Node = Nodes->getNodeAs<T>("");
4571 return verify(*Nodes, *Context, Node);
4572 }
4573
4574 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004575 // Use the original typed pointer to verify we can pass pointers to subtypes
4576 // to equalsNode.
4577 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004578 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004579 "", match(stmt(hasParent(
4580 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004581 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004582 }
4583 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004584 // Use the original typed pointer to verify we can pass pointers to subtypes
4585 // to equalsNode.
4586 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004587 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004588 "", match(decl(hasParent(
4589 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004590 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004591 }
4592};
4593
4594TEST(IsEqualTo, MatchesNodesByIdentity) {
4595 EXPECT_TRUE(matchAndVerifyResultTrue(
4596 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004597 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4598 EXPECT_TRUE(matchAndVerifyResultTrue(
4599 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4600 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004601}
4602
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004603TEST(MatchFinder, CheckProfiling) {
4604 MatchFinder::MatchFinderOptions Options;
4605 llvm::StringMap<llvm::TimeRecord> Records;
4606 Options.CheckProfiling.emplace(Records);
4607 MatchFinder Finder(std::move(Options));
4608
4609 struct NamedCallback : public MatchFinder::MatchCallback {
4610 void run(const MatchFinder::MatchResult &Result) override {}
4611 StringRef getID() const override { return "MyID"; }
4612 } Callback;
4613 Finder.addMatcher(decl(), &Callback);
4614 std::unique_ptr<FrontendActionFactory> Factory(
4615 newFrontendActionFactory(&Finder));
4616 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4617
4618 EXPECT_EQ(1u, Records.size());
4619 EXPECT_EQ("MyID", Records.begin()->getKey());
4620}
4621
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004622class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4623public:
4624 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004625 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004626 EXPECT_TRUE(Called);
4627 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004628 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004629 bool Called;
4630};
4631
4632TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4633 MatchFinder Finder;
4634 VerifyStartOfTranslationUnit VerifyCallback;
4635 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004636 std::unique_ptr<FrontendActionFactory> Factory(
4637 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004638 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4639 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004640
4641 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004642 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004643 ASSERT_TRUE(AST.get());
4644 Finder.matchAST(AST->getASTContext());
4645 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004646}
4647
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004648class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4649public:
4650 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004651 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004652 EXPECT_FALSE(Called);
4653 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004654 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004655 bool Called;
4656};
4657
4658TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4659 MatchFinder Finder;
4660 VerifyEndOfTranslationUnit VerifyCallback;
4661 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004662 std::unique_ptr<FrontendActionFactory> Factory(
4663 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004664 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4665 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004666
4667 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004668 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004669 ASSERT_TRUE(AST.get());
4670 Finder.matchAST(AST->getASTContext());
4671 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004672}
4673
Manuel Klimekbbb75852013-06-20 14:06:32 +00004674TEST(EqualsBoundNodeMatcher, QualType) {
4675 EXPECT_TRUE(matches(
4676 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4677 hasInitializer(ignoringParenImpCasts(
4678 hasType(qualType(equalsBoundNode("type"))))))));
4679 EXPECT_TRUE(notMatches("int i = 1.f;",
4680 varDecl(hasType(qualType().bind("type")),
4681 hasInitializer(ignoringParenImpCasts(hasType(
4682 qualType(equalsBoundNode("type"))))))));
4683}
4684
4685TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4686 EXPECT_TRUE(notMatches(
4687 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4688 hasInitializer(ignoringParenImpCasts(
4689 hasType(qualType(equalsBoundNode("type"))))))));
4690}
4691
4692TEST(EqualsBoundNodeMatcher, Stmt) {
4693 EXPECT_TRUE(
4694 matches("void f() { if(true) {} }",
4695 stmt(allOf(ifStmt().bind("if"),
4696 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4697
4698 EXPECT_TRUE(notMatches(
4699 "void f() { if(true) { if (true) {} } }",
4700 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4701}
4702
4703TEST(EqualsBoundNodeMatcher, Decl) {
4704 EXPECT_TRUE(matches(
4705 "class X { class Y {}; };",
4706 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4707 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4708
4709 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4710 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4711 has(decl(equalsBoundNode("record")))))));
4712}
4713
4714TEST(EqualsBoundNodeMatcher, Type) {
4715 EXPECT_TRUE(matches(
4716 "class X { int a; int b; };",
4717 recordDecl(
4718 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4719 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4720
4721 EXPECT_TRUE(notMatches(
4722 "class X { int a; double b; };",
4723 recordDecl(
4724 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4725 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4726}
4727
4728TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004729 EXPECT_TRUE(matchAndVerifyResultTrue(
4730 "int f() {"
4731 " if (1) {"
4732 " int i = 9;"
4733 " }"
4734 " int j = 10;"
4735 " {"
4736 " float k = 9.0;"
4737 " }"
4738 " return 0;"
4739 "}",
4740 // Look for variable declarations within functions whose type is the same
4741 // as the function return type.
4742 functionDecl(returns(qualType().bind("type")),
4743 forEachDescendant(varDecl(hasType(
4744 qualType(equalsBoundNode("type")))).bind("decl"))),
4745 // Only i and j should match, not k.
4746 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4747}
4748
4749TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4750 EXPECT_TRUE(matchAndVerifyResultTrue(
4751 "void f() {"
4752 " int x;"
4753 " double d;"
4754 " x = d + x - d + x;"
4755 "}",
4756 functionDecl(
4757 hasName("f"), forEachDescendant(varDecl().bind("d")),
4758 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4759 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4760}
4761
Manuel Klimekce68f772014-03-25 14:39:26 +00004762TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4763 EXPECT_TRUE(matchAndVerifyResultTrue(
4764 "struct StringRef { int size() const; const char* data() const; };"
4765 "void f(StringRef v) {"
4766 " v.data();"
4767 "}",
4768 memberCallExpr(
4769 callee(methodDecl(hasName("data"))),
4770 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4771 .bind("var")))),
4772 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4773 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4774 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4775 .bind("data"),
4776 new VerifyIdIsBoundTo<Expr>("data", 1)));
4777
4778 EXPECT_FALSE(matches(
4779 "struct StringRef { int size() const; const char* data() const; };"
4780 "void f(StringRef v) {"
4781 " v.data();"
4782 " v.size();"
4783 "}",
4784 memberCallExpr(
4785 callee(methodDecl(hasName("data"))),
4786 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4787 .bind("var")))),
4788 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4789 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4790 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4791 .bind("data")));
4792}
4793
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004794TEST(TypeDefDeclMatcher, Match) {
4795 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4796 typedefDecl(hasName("typedefDeclTest"))));
4797}
4798
Aaron Ballman11825f22015-08-18 19:55:20 +00004799TEST(IsInlineMatcher, IsInline) {
4800 EXPECT_TRUE(matches("void g(); inline void f();",
4801 functionDecl(isInline(), hasName("f"))));
4802 EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
4803 namespaceDecl(isInline(), hasName("m"))));
4804}
4805
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004806// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4807#ifndef LLVM_ON_WIN32
4808
4809TEST(Matcher, IsExpansionInMainFileMatcher) {
4810 EXPECT_TRUE(matches("class X {};",
4811 recordDecl(hasName("X"), isExpansionInMainFile())));
4812 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4813 FileContentMappings M;
4814 M.push_back(std::make_pair("/other", "class X {};"));
4815 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4816 recordDecl(isExpansionInMainFile()), false,
4817 "-isystem/", M));
4818}
4819
4820TEST(Matcher, IsExpansionInSystemHeader) {
4821 FileContentMappings M;
4822 M.push_back(std::make_pair("/other", "class X {};"));
4823 EXPECT_TRUE(matchesConditionally(
4824 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4825 "-isystem/", M));
4826 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4827 recordDecl(isExpansionInSystemHeader()),
4828 false, "-I/", M));
4829 EXPECT_TRUE(notMatches("class X {};",
4830 recordDecl(isExpansionInSystemHeader())));
4831 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4832}
4833
4834TEST(Matcher, IsExpansionInFileMatching) {
4835 FileContentMappings M;
4836 M.push_back(std::make_pair("/foo", "class A {};"));
4837 M.push_back(std::make_pair("/bar", "class B {};"));
4838 EXPECT_TRUE(matchesConditionally(
4839 "#include <foo>\n"
4840 "#include <bar>\n"
4841 "class X {};",
4842 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4843 "-isystem/", M));
4844 EXPECT_TRUE(matchesConditionally(
4845 "#include <foo>\n"
4846 "#include <bar>\n"
4847 "class X {};",
4848 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4849 "-isystem/", M));
4850}
4851
4852#endif // LLVM_ON_WIN32
4853
Manuel Klimekbfa43572015-03-12 15:48:15 +00004854
4855TEST(ObjCMessageExprMatcher, SimpleExprs) {
4856 // don't find ObjCMessageExpr where none are present
4857 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
4858
4859 std::string Objc1String =
4860 "@interface Str "
4861 " - (Str *)uppercaseString:(Str *)str;"
4862 "@end "
4863 "@interface foo "
4864 "- (void)meth:(Str *)text;"
4865 "@end "
4866 " "
4867 "@implementation foo "
4868 "- (void) meth:(Str *)text { "
4869 " [self contents];"
4870 " Str *up = [text uppercaseString];"
4871 "} "
4872 "@end ";
4873 EXPECT_TRUE(matchesObjC(
4874 Objc1String,
4875 objcMessageExpr(anything())));
4876 EXPECT_TRUE(matchesObjC(
4877 Objc1String,
4878 objcMessageExpr(hasSelector("contents"))));
4879 EXPECT_TRUE(matchesObjC(
4880 Objc1String,
4881 objcMessageExpr(matchesSelector("cont*"))));
4882 EXPECT_FALSE(matchesObjC(
4883 Objc1String,
4884 objcMessageExpr(matchesSelector("?cont*"))));
4885 EXPECT_TRUE(notMatchesObjC(
4886 Objc1String,
4887 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
4888 EXPECT_TRUE(matchesObjC(
4889 Objc1String,
4890 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
4891 EXPECT_TRUE(matchesObjC(
4892 Objc1String,
4893 objcMessageExpr(matchesSelector("uppercase*"),
4894 argumentCountIs(0)
4895 )));
4896
4897}
4898
Manuel Klimek04616e42012-07-06 05:48:52 +00004899} // end namespace ast_matchers
4900} // end namespace clang