blob: 8f2123ac9c40c7dce100db7bf85358104835dbbc [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
Aaron Ballmanb85be662015-09-11 11:51:24 +0000927TEST(TypeMatcher, MatchesDeclTypes) {
928 // TypedefType -> TypedefNameDecl
929 EXPECT_TRUE(matches("typedef int I; void f(I i);",
930 parmVarDecl(hasType(namedDecl(hasName("I"))))));
931 // ObjCObjectPointerType
932 EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);",
933 parmVarDecl(hasType(objcObjectPointerType()))));
934 // ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl
935 EXPECT_TRUE(matchesObjC(
936 "@interface Foo @end void f(Foo *f);",
937 parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo")))))));
938 // TemplateTypeParmType
939 EXPECT_TRUE(matches("template <typename T> void f(T t);",
940 parmVarDecl(hasType(templateTypeParmType()))));
941 // TemplateTypeParmType -> TemplateTypeParmDecl
942 EXPECT_TRUE(matches("template <typename T> void f(T t);",
943 parmVarDecl(hasType(namedDecl(hasName("T"))))));
944 // InjectedClassNameType
945 EXPECT_TRUE(matches("template <typename T> struct S {"
946 " void f(S s);"
947 "};",
948 parmVarDecl(hasType(injectedClassNameType()))));
949 EXPECT_TRUE(notMatches("template <typename T> struct S {"
950 " void g(S<T> s);"
951 "};",
952 parmVarDecl(hasType(injectedClassNameType()))));
953 // InjectedClassNameType -> CXXRecordDecl
954 EXPECT_TRUE(matches("template <typename T> struct S {"
955 " void f(S s);"
956 "};",
957 parmVarDecl(hasType(namedDecl(hasName("S"))))));
958
959 static const char Using[] = "template <typename T>"
960 "struct Base {"
961 " typedef T Foo;"
962 "};"
963 ""
964 "template <typename T>"
965 "struct S : private Base<T> {"
966 " using typename Base<T>::Foo;"
967 " void f(Foo);"
968 "};";
969 // UnresolvedUsingTypenameDecl
970 EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo"))));
971 // UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl
972 EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo"))))));
973}
974
Manuel Klimek04616e42012-07-06 05:48:52 +0000975TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000976 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000977
978 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000979 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000980
981 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000982 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000983
984 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000985 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000986
987 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
988 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000989 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000990
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000991 StatementMatcher MethodX =
992 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000993
994 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
995 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000996 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000997}
998
999TEST(Matcher, BindTheSameNameInAlternatives) {
1000 StatementMatcher matcher = anyOf(
1001 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001002 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +00001003 hasRHS(integerLiteral(equals(0)))),
1004 binaryOperator(hasOperatorName("+"),
1005 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001006 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001007
1008 EXPECT_TRUE(matchAndVerifyResultTrue(
1009 // The first branch of the matcher binds x to 0 but then fails.
1010 // The second branch binds x to f() and succeeds.
1011 "int f() { return 0 + f(); }",
1012 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00001013 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001014}
1015
Manuel Klimekfdf98762012-08-30 19:41:06 +00001016TEST(Matcher, BindsIDForMemoizedResults) {
1017 // Using the same matcher in two match expressions will make memoization
1018 // kick in.
1019 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
1020 EXPECT_TRUE(matchAndVerifyResultTrue(
1021 "class A { class B { class X {}; }; };",
1022 DeclarationMatcher(anyOf(
1023 recordDecl(hasName("A"), hasDescendant(ClassX)),
1024 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00001025 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +00001026}
1027
Daniel Jasper856194d02012-12-03 15:43:25 +00001028TEST(HasDeclaration, HasDeclarationOfEnumType) {
1029 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
1030 expr(hasType(pointsTo(
1031 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
1032}
1033
Edwin Vaneed936452013-02-25 14:32:42 +00001034TEST(HasDeclaration, HasGetDeclTraitTest) {
1035 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
1036 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
1037 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
1038}
1039
Edwin Vane2c197e02013-02-19 17:14:34 +00001040TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
1041 EXPECT_TRUE(matches("typedef int X; X a;",
1042 varDecl(hasName("a"),
1043 hasType(typedefType(hasDeclaration(decl()))))));
1044
1045 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
1046}
1047
Edwin Vanef901b712013-02-25 14:49:29 +00001048TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
1049 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
1050 varDecl(hasType(templateSpecializationType(
1051 hasDeclaration(namedDecl(hasName("A"))))))));
1052}
1053
Manuel Klimek04616e42012-07-06 05:48:52 +00001054TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001055 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001056 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001057 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001058 EXPECT_TRUE(
1059 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001060 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001061 EXPECT_TRUE(
1062 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001063 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001064}
1065
1066TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001067 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001068 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001069 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001070 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001071 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001072 EXPECT_TRUE(
1073 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001074 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001075}
1076
1077TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001078 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001079 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001080 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001081 EXPECT_TRUE(
1082 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001083 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001084}
1085
1086TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001087 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001088 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001089 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001090 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001091 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001092}
1093
Manuel Klimekc16c6522013-06-20 13:08:29 +00001094TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1095 EXPECT_TRUE(matches("int x;",
1096 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1097
1098 // Make sure we don't crash on implicit constructors.
1099 EXPECT_TRUE(notMatches("class X {}; X x;",
1100 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1101}
1102
Manuel Klimek04616e42012-07-06 05:48:52 +00001103TEST(Matcher, Call) {
1104 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001105 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001106 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001107
1108 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1109 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1110
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001111 StatementMatcher MethodOnY =
1112 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001113
1114 EXPECT_TRUE(
1115 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1116 MethodOnY));
1117 EXPECT_TRUE(
1118 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1119 MethodOnY));
1120 EXPECT_TRUE(
1121 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1122 MethodOnY));
1123 EXPECT_TRUE(
1124 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1125 MethodOnY));
1126 EXPECT_TRUE(
1127 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1128 MethodOnY));
1129
1130 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001131 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001132
1133 EXPECT_TRUE(
1134 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1135 MethodOnYPointer));
1136 EXPECT_TRUE(
1137 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1138 MethodOnYPointer));
1139 EXPECT_TRUE(
1140 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1141 MethodOnYPointer));
1142 EXPECT_TRUE(
1143 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1144 MethodOnYPointer));
1145 EXPECT_TRUE(
1146 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1147 MethodOnYPointer));
1148}
1149
Daniel Jasper5901e472012-10-01 13:40:41 +00001150TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001151 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001152 lambdaExpr()));
1153}
1154
1155TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001156 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1157 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001158 forRangeStmt()));
1159 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1160 forRangeStmt()));
1161}
1162
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001163TEST(Matcher, SubstNonTypeTemplateParm) {
1164 EXPECT_FALSE(matches("template<int N>\n"
1165 "struct A { static const int n = 0; };\n"
1166 "struct B : public A<42> {};",
1167 substNonTypeTemplateParmExpr()));
1168 EXPECT_TRUE(matches("template<int N>\n"
1169 "struct A { static const int n = N; };\n"
1170 "struct B : public A<42> {};",
1171 substNonTypeTemplateParmExpr()));
1172}
1173
Daniel Jasper5901e472012-10-01 13:40:41 +00001174TEST(Matcher, UserDefinedLiteral) {
1175 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1176 " return i + 1;"
1177 "}"
1178 "char c = 'a'_inc;",
1179 userDefinedLiteral()));
1180}
1181
Daniel Jasper87c3d362012-09-20 14:12:57 +00001182TEST(Matcher, FlowControl) {
1183 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1184 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1185 continueStmt()));
1186 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1187 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1188 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1189}
1190
Daniel Jasper1dad1832012-07-10 20:20:19 +00001191TEST(HasType, MatchesAsString) {
1192 EXPECT_TRUE(
1193 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001194 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001195 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001196 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001197 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001198 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001199 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001200 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001201}
1202
Manuel Klimek04616e42012-07-06 05:48:52 +00001203TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001204 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001205 // Unary operator
1206 EXPECT_TRUE(matches("class Y { }; "
1207 "bool operator!(Y x) { return false; }; "
1208 "Y y; bool c = !y;", OpCall));
1209 // No match -- special operators like "new", "delete"
1210 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1211 // we need to figure out include paths in the test.
1212 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1213 // "class Y { }; "
1214 // "void *operator new(size_t size) { return 0; } "
1215 // "Y *y = new Y;", OpCall));
1216 EXPECT_TRUE(notMatches("class Y { }; "
1217 "void operator delete(void *p) { } "
1218 "void a() {Y *y = new Y; delete y;}", OpCall));
1219 // Binary operator
1220 EXPECT_TRUE(matches("class Y { }; "
1221 "bool operator&&(Y x, Y y) { return true; }; "
1222 "Y a; Y b; bool c = a && b;",
1223 OpCall));
1224 // No match -- normal operator, not an overloaded one.
1225 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1226 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1227}
1228
1229TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1230 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001231 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001232 EXPECT_TRUE(matches("class Y { }; "
1233 "bool operator&&(Y x, Y y) { return true; }; "
1234 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1235 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001236 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001237 EXPECT_TRUE(notMatches("class Y { }; "
1238 "bool operator&&(Y x, Y y) { return true; }; "
1239 "Y a; Y b; bool c = a && b;",
1240 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001241 StatementMatcher OpStarCall =
1242 operatorCallExpr(hasOverloadedOperatorName("*"));
1243 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1244 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001245 DeclarationMatcher ClassWithOpStar =
1246 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1247 EXPECT_TRUE(matches("class Y { int operator*(); };",
1248 ClassWithOpStar));
1249 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1250 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001251 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1252 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1253 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001254}
1255
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001256TEST(Matcher, NestedOverloadedOperatorCalls) {
1257 EXPECT_TRUE(matchAndVerifyResultTrue(
1258 "class Y { }; "
1259 "Y& operator&&(Y& x, Y& y) { return x; }; "
1260 "Y a; Y b; Y c; Y d = a && b && c;",
1261 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1262 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1263 EXPECT_TRUE(matches(
1264 "class Y { }; "
1265 "Y& operator&&(Y& x, Y& y) { return x; }; "
1266 "Y a; Y b; Y c; Y d = a && b && c;",
1267 operatorCallExpr(hasParent(operatorCallExpr()))));
1268 EXPECT_TRUE(matches(
1269 "class Y { }; "
1270 "Y& operator&&(Y& x, Y& y) { return x; }; "
1271 "Y a; Y b; Y c; Y d = a && b && c;",
1272 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1273}
1274
Manuel Klimek04616e42012-07-06 05:48:52 +00001275TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001276 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001277 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001278
1279 EXPECT_TRUE(
1280 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1281 MethodOnY));
1282 EXPECT_TRUE(
1283 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1284 MethodOnY));
1285 EXPECT_TRUE(
1286 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1287 MethodOnY));
1288 EXPECT_TRUE(
1289 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1290 MethodOnY));
1291 EXPECT_TRUE(
1292 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1293 MethodOnY));
1294
1295 EXPECT_TRUE(matches(
1296 "class Y {"
1297 " public: virtual void x();"
1298 "};"
1299 "class X : public Y {"
1300 " public: virtual void x();"
1301 "};"
1302 "void z() { X *x; x->Y::x(); }", MethodOnY));
1303}
1304
1305TEST(Matcher, VariableUsage) {
1306 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001307 declRefExpr(to(
1308 varDecl(hasInitializer(
1309 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001310
1311 EXPECT_TRUE(matches(
1312 "class Y {"
1313 " public:"
1314 " bool x() const;"
1315 "};"
1316 "void z(const Y &y) {"
1317 " bool b = y.x();"
1318 " if (b) {}"
1319 "}", Reference));
1320
1321 EXPECT_TRUE(notMatches(
1322 "class Y {"
1323 " public:"
1324 " bool x() const;"
1325 "};"
1326 "void z(const Y &y) {"
1327 " bool b = y.x();"
1328 "}", Reference));
1329}
1330
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001331TEST(Matcher, VarDecl_Storage) {
1332 auto M = varDecl(hasName("X"), hasLocalStorage());
1333 EXPECT_TRUE(matches("void f() { int X; }", M));
1334 EXPECT_TRUE(notMatches("int X;", M));
1335 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1336
1337 M = varDecl(hasName("X"), hasGlobalStorage());
1338 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1339 EXPECT_TRUE(matches("int X;", M));
1340 EXPECT_TRUE(matches("void f() { static int X; }", M));
1341}
1342
Manuel Klimek61379422012-12-04 14:42:08 +00001343TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001344 EXPECT_TRUE(matches(
1345 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001346 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001347}
1348
Manuel Klimek04616e42012-07-06 05:48:52 +00001349TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001350 StatementMatcher CallOnVariableY =
1351 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001352
1353 EXPECT_TRUE(matches(
1354 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1355 EXPECT_TRUE(matches(
1356 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1357 EXPECT_TRUE(matches(
1358 "class Y { public: void x(); };"
1359 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1360 EXPECT_TRUE(matches(
1361 "class Y { public: void x(); };"
1362 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1363 EXPECT_TRUE(notMatches(
1364 "class Y { public: void x(); };"
1365 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1366 CallOnVariableY));
1367}
1368
Daniel Jasper1dad1832012-07-10 20:20:19 +00001369TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1370 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1371 unaryExprOrTypeTraitExpr()));
1372 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1373 alignOfExpr(anything())));
1374 // FIXME: Uncomment once alignof is enabled.
1375 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1376 // unaryExprOrTypeTraitExpr()));
1377 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1378 // sizeOfExpr()));
1379}
1380
1381TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1382 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1383 hasArgumentOfType(asString("int")))));
1384 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1385 hasArgumentOfType(asString("float")))));
1386 EXPECT_TRUE(matches(
1387 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001388 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001389 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001390 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001391}
1392
Manuel Klimek04616e42012-07-06 05:48:52 +00001393TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001394 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001395}
1396
1397TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001398 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001399}
1400
1401TEST(MemberExpression, MatchesVariable) {
1402 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001403 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001404 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001405 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001406 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001407 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001408}
1409
1410TEST(MemberExpression, MatchesStaticVariable) {
1411 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001412 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001413 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001414 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001415 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001416 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001417}
1418
Daniel Jasper4e566c42012-07-12 08:50:38 +00001419TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001420 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1421 EXPECT_TRUE(matches(
1422 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1423 callExpr(hasArgument(0, declRefExpr(
1424 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001425}
1426
1427TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001428 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001429 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001430 callExpr(hasArgument(0, declRefExpr(
1431 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001432}
1433
Manuel Klimek04616e42012-07-06 05:48:52 +00001434TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1435 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001436 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001437 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001438 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001439 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001440 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001441}
1442
1443TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1444 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001445 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001446 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001447 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001448 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001449 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001450}
1451
1452TEST(IsArrow, MatchesMemberCallsViaArrow) {
1453 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001454 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001455 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001456 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001457 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001458 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001459}
1460
1461TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001462 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001463
1464 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1465 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001466
1467 CallMethodX = callExpr(callee(conversionDecl()));
1468 EXPECT_TRUE(
1469 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1470 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1471 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001472}
1473
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001474TEST(ConversionDeclaration, IsExplicit) {
1475 EXPECT_TRUE(matches("struct S { explicit operator int(); };",
1476 conversionDecl(isExplicit())));
1477 EXPECT_TRUE(notMatches("struct S { operator int(); };",
1478 conversionDecl(isExplicit())));
1479}
1480
Manuel Klimek04616e42012-07-06 05:48:52 +00001481TEST(Callee, MatchesMemberExpressions) {
1482 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001483 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001484 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001485 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001486}
1487
1488TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001489 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001490
1491 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1492 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1493
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001494 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1495 llvm::Triple::Win32) {
1496 // FIXME: Make this work for MSVC.
1497 // Dependent contexts, but a non-dependent call.
1498 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1499 CallFunctionF));
1500 EXPECT_TRUE(
1501 matches("void f(); template <int N> struct S { void g() { f(); } };",
1502 CallFunctionF));
1503 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001504
1505 // Depedent calls don't match.
1506 EXPECT_TRUE(
1507 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1508 CallFunctionF));
1509 EXPECT_TRUE(
1510 notMatches("void f(int);"
1511 "template <typename T> struct S { void g(T t) { f(t); } };",
1512 CallFunctionF));
1513}
1514
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001515TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1516 EXPECT_TRUE(
1517 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001518 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001519}
1520
1521TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1522 EXPECT_TRUE(
1523 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001524 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001525}
1526
1527TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1528 EXPECT_TRUE(
1529 notMatches("void g(); template <typename T> void f(T t) {}"
1530 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001531 functionTemplateDecl(hasName("f"),
1532 hasDescendant(declRefExpr(to(
1533 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001534}
1535
Manuel Klimek04616e42012-07-06 05:48:52 +00001536TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001537 StatementMatcher CallArgumentY = callExpr(
1538 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001539
1540 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1541 EXPECT_TRUE(
1542 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1543 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1544
Daniel Jasper848cbe12012-09-18 13:09:13 +00001545 StatementMatcher WrongIndex = callExpr(
1546 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001547 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1548}
1549
1550TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001551 StatementMatcher CallArgumentY = callExpr(
1552 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001553 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1554 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1555 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1556}
1557
1558TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001559 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001560
1561 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1562 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1563 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1564}
1565
Daniel Jasper9f501292012-12-04 11:54:27 +00001566TEST(Matcher, ParameterCount) {
1567 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1568 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1569 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1570 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1571 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1572}
1573
Manuel Klimek04616e42012-07-06 05:48:52 +00001574TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001575 DeclarationMatcher ReferenceClassX = varDecl(
1576 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001577 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1578 ReferenceClassX));
1579 EXPECT_TRUE(
1580 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001581 // The match here is on the implicit copy constructor code for
1582 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001583 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001584 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1585 EXPECT_TRUE(
1586 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001587 EXPECT_TRUE(
1588 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1589}
1590
Edwin Vane0a4836e2013-03-06 17:02:57 +00001591TEST(QualType, hasCanonicalType) {
1592 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1593 "int a;"
1594 "int_ref b = a;",
1595 varDecl(hasType(qualType(referenceType())))));
1596 EXPECT_TRUE(
1597 matches("typedef int &int_ref;"
1598 "int a;"
1599 "int_ref b = a;",
1600 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1601}
1602
Edwin Vane119d3df2013-04-02 18:15:55 +00001603TEST(QualType, hasLocalQualifiers) {
1604 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1605 varDecl(hasType(hasLocalQualifiers()))));
1606 EXPECT_TRUE(matches("int *const j = nullptr;",
1607 varDecl(hasType(hasLocalQualifiers()))));
1608 EXPECT_TRUE(matches("int *volatile k;",
1609 varDecl(hasType(hasLocalQualifiers()))));
1610 EXPECT_TRUE(notMatches("int m;",
1611 varDecl(hasType(hasLocalQualifiers()))));
1612}
1613
Manuel Klimek04616e42012-07-06 05:48:52 +00001614TEST(HasParameter, CallsInnerMatcher) {
1615 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001616 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001617 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001618 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001619}
1620
1621TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1622 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001623 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001624}
1625
1626TEST(HasType, MatchesParameterVariableTypesStrictly) {
1627 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001628 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001629 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001630 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001631 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001632 methodDecl(hasParameter(0,
1633 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001634 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001635 methodDecl(hasParameter(0,
1636 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001637}
1638
1639TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1640 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001641 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001642 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001643 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001644}
1645
Daniel Jasper1dad1832012-07-10 20:20:19 +00001646TEST(Returns, MatchesReturnTypes) {
1647 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001648 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001649 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001650 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001651 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001652 functionDecl(returns(hasDeclaration(
1653 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001654}
1655
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001656TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001657 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1658 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1659 functionDecl(isExternC())));
1660 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001661}
1662
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001663TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1664 EXPECT_TRUE(
1665 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1666 EXPECT_TRUE(matches("void Func() = delete;",
1667 functionDecl(hasName("Func"), isDeleted())));
1668}
1669
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001670TEST(isConstexpr, MatchesConstexprDeclarations) {
1671 EXPECT_TRUE(matches("constexpr int foo = 42;",
1672 varDecl(hasName("foo"), isConstexpr())));
1673 EXPECT_TRUE(matches("constexpr int bar();",
1674 functionDecl(hasName("bar"), isConstexpr())));
1675}
1676
Manuel Klimek04616e42012-07-06 05:48:52 +00001677TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1678 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001679 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001680}
1681
1682TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1683 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001684 methodDecl(hasAnyParameter(hasType(pointsTo(
1685 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001686}
1687
Alp Toker8db6e7a2014-01-05 06:38:57 +00001688TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001689 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001690 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001691 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001692 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001693}
1694
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001695TEST(Matcher, MatchesClassTemplateSpecialization) {
1696 EXPECT_TRUE(matches("template<typename T> struct A {};"
1697 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001698 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001699 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001700 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001701 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001702 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001703}
1704
Manuel Klimekc16c6522013-06-20 13:08:29 +00001705TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1706 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1707 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1708}
1709
1710TEST(ParmVarDecl, MatchesParmVars) {
1711 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1712 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1713}
1714
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001715TEST(Matcher, MatchesTypeTemplateArgument) {
1716 EXPECT_TRUE(matches(
1717 "template<typename T> struct B {};"
1718 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001719 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001720 asString("int"))))));
1721}
1722
1723TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1724 EXPECT_TRUE(matches(
1725 "struct B { int next; };"
1726 "template<int(B::*next_ptr)> struct A {};"
1727 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001728 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1729 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001730
1731 EXPECT_TRUE(notMatches(
1732 "template <typename T> struct A {};"
1733 "A<int> a;",
1734 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1735 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001736
1737 EXPECT_TRUE(matches(
1738 "struct B { int next; };"
1739 "template<int(B::*next_ptr)> struct A {};"
1740 "A<&B::next> a;",
1741 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1742 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1743
1744 EXPECT_TRUE(notMatches(
1745 "template <typename T> struct A {};"
1746 "A<int> a;",
1747 templateSpecializationType(hasAnyTemplateArgument(
1748 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001749}
1750
1751TEST(Matcher, MatchesSpecificArgument) {
1752 EXPECT_TRUE(matches(
1753 "template<typename T, typename U> class A {};"
1754 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001755 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001756 1, refersToType(asString("int"))))));
1757 EXPECT_TRUE(notMatches(
1758 "template<typename T, typename U> class A {};"
1759 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001760 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001761 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001762
1763 EXPECT_TRUE(matches(
1764 "template<typename T, typename U> class A {};"
1765 "A<bool, int> a;",
1766 templateSpecializationType(hasTemplateArgument(
1767 1, refersToType(asString("int"))))));
1768 EXPECT_TRUE(notMatches(
1769 "template<typename T, typename U> class A {};"
1770 "A<int, bool> a;",
1771 templateSpecializationType(hasTemplateArgument(
1772 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001773}
1774
Manuel Klimek7735e402014-10-09 13:06:22 +00001775TEST(TemplateArgument, Matches) {
1776 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1777 classTemplateSpecializationDecl(
1778 hasAnyTemplateArgument(templateArgument()))));
1779 EXPECT_TRUE(matches(
1780 "template<typename T> struct C {}; C<int> c;",
1781 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1782}
1783
1784TEST(TemplateArgumentCountIs, Matches) {
1785 EXPECT_TRUE(
1786 matches("template<typename T> struct C {}; C<int> c;",
1787 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1788 EXPECT_TRUE(
1789 notMatches("template<typename T> struct C {}; C<int> c;",
1790 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1791
1792 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1793 templateSpecializationType(templateArgumentCountIs(1))));
1794 EXPECT_TRUE(
1795 notMatches("template<typename T> struct C {}; C<int> c;",
1796 templateSpecializationType(templateArgumentCountIs(2))));
1797}
1798
1799TEST(IsIntegral, Matches) {
1800 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1801 classTemplateSpecializationDecl(
1802 hasAnyTemplateArgument(isIntegral()))));
1803 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1804 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1805 templateArgument(isIntegral())))));
1806}
1807
1808TEST(RefersToIntegralType, Matches) {
1809 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1810 classTemplateSpecializationDecl(
1811 hasAnyTemplateArgument(refersToIntegralType(
1812 asString("int"))))));
1813 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1814 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1815 refersToIntegralType(asString("int"))))));
1816}
1817
1818TEST(EqualsIntegralValue, Matches) {
1819 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1820 classTemplateSpecializationDecl(
1821 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1822 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1823 classTemplateSpecializationDecl(
1824 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1825 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1826 classTemplateSpecializationDecl(
1827 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1828 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1829 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1830 equalsIntegralValue("0042")))));
1831}
1832
Daniel Jasper639522c2013-02-25 12:02:08 +00001833TEST(Matcher, MatchesAccessSpecDecls) {
1834 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1835 EXPECT_TRUE(
1836 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1837 EXPECT_TRUE(
1838 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1839 EXPECT_TRUE(
1840 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1841
1842 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1843}
1844
Aaron Ballman41143bb2015-07-24 12:35:41 +00001845TEST(Matcher, MatchesFinal) {
1846 EXPECT_TRUE(matches("class X final {};", recordDecl(isFinal())));
1847 EXPECT_TRUE(matches("class X { virtual void f() final; };",
1848 methodDecl(isFinal())));
1849 EXPECT_TRUE(notMatches("class X {};", recordDecl(isFinal())));
1850 EXPECT_TRUE(notMatches("class X { virtual void f(); };",
1851 methodDecl(isFinal())));
1852}
1853
Edwin Vane37ee1d72013-04-09 20:46:36 +00001854TEST(Matcher, MatchesVirtualMethod) {
1855 EXPECT_TRUE(matches("class X { virtual int f(); };",
1856 methodDecl(isVirtual(), hasName("::X::f"))));
1857 EXPECT_TRUE(notMatches("class X { int f(); };",
1858 methodDecl(isVirtual())));
1859}
1860
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001861TEST(Matcher, MatchesPureMethod) {
1862 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1863 methodDecl(isPure(), hasName("::X::f"))));
1864 EXPECT_TRUE(notMatches("class X { int f(); };",
1865 methodDecl(isPure())));
1866}
1867
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001868TEST(Matcher, MatchesConstMethod) {
1869 EXPECT_TRUE(matches("struct A { void foo() const; };",
1870 methodDecl(isConst())));
1871 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1872 methodDecl(isConst())));
1873}
1874
Edwin Vane37ee1d72013-04-09 20:46:36 +00001875TEST(Matcher, MatchesOverridingMethod) {
1876 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1877 "class Y : public X { int f(); };",
1878 methodDecl(isOverride(), hasName("::Y::f"))));
1879 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1880 "class Y : public X { int f(); };",
1881 methodDecl(isOverride(), hasName("::X::f"))));
1882 EXPECT_TRUE(notMatches("class X { int f(); }; "
1883 "class Y : public X { int f(); };",
1884 methodDecl(isOverride())));
1885 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1886 methodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001887 EXPECT_TRUE(
1888 matches("template <typename Base> struct Y : Base { void f() override;};",
1889 methodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001890}
1891
Manuel Klimek04616e42012-07-06 05:48:52 +00001892TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001893 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001894
1895 EXPECT_TRUE(
1896 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1897 EXPECT_TRUE(
1898 matches("class X { public: X(); }; void x() { X x = X(); }",
1899 Constructor));
1900 EXPECT_TRUE(
1901 matches("class X { public: X(int); }; void x() { X x = 0; }",
1902 Constructor));
1903 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1904}
1905
1906TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001907 StatementMatcher Constructor = constructExpr(
1908 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001909
1910 EXPECT_TRUE(
1911 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1912 Constructor));
1913 EXPECT_TRUE(
1914 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1915 Constructor));
1916 EXPECT_TRUE(
1917 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1918 Constructor));
1919 EXPECT_TRUE(
1920 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1921 Constructor));
1922
Daniel Jasper848cbe12012-09-18 13:09:13 +00001923 StatementMatcher WrongIndex = constructExpr(
1924 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001925 EXPECT_TRUE(
1926 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1927 WrongIndex));
1928}
1929
1930TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001931 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001932
1933 EXPECT_TRUE(
1934 matches("class X { public: X(int); }; void x() { X x(0); }",
1935 Constructor1Arg));
1936 EXPECT_TRUE(
1937 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1938 Constructor1Arg));
1939 EXPECT_TRUE(
1940 matches("class X { public: X(int); }; void x() { X x = 0; }",
1941 Constructor1Arg));
1942 EXPECT_TRUE(
1943 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1944 Constructor1Arg));
1945}
1946
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001947TEST(Matcher, ConstructorListInitialization) {
1948 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1949
1950 EXPECT_TRUE(
1951 matches("class X { public: X(int); }; void x() { X x{0}; }",
1952 ConstructorListInit));
1953 EXPECT_FALSE(
1954 matches("class X { public: X(int); }; void x() { X x(0); }",
1955 ConstructorListInit));
1956}
1957
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001958TEST(Matcher,ThisExpr) {
1959 EXPECT_TRUE(
1960 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1961 EXPECT_TRUE(
1962 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1963}
1964
Manuel Klimek04616e42012-07-06 05:48:52 +00001965TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001966 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001967
1968 std::string ClassString = "class string { public: string(); ~string(); }; ";
1969
1970 EXPECT_TRUE(
1971 matches(ClassString +
1972 "string GetStringByValue();"
1973 "void FunctionTakesString(string s);"
1974 "void run() { FunctionTakesString(GetStringByValue()); }",
1975 TempExpression));
1976
1977 EXPECT_TRUE(
1978 notMatches(ClassString +
1979 "string* GetStringPointer(); "
1980 "void FunctionTakesStringPtr(string* s);"
1981 "void run() {"
1982 " string* s = GetStringPointer();"
1983 " FunctionTakesStringPtr(GetStringPointer());"
1984 " FunctionTakesStringPtr(s);"
1985 "}",
1986 TempExpression));
1987
1988 EXPECT_TRUE(
1989 notMatches("class no_dtor {};"
1990 "no_dtor GetObjByValue();"
1991 "void ConsumeObj(no_dtor param);"
1992 "void run() { ConsumeObj(GetObjByValue()); }",
1993 TempExpression));
1994}
1995
Sam Panzer68a35af2012-08-24 22:04:44 +00001996TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1997 std::string ClassString =
1998 "class string { public: string(); int length(); }; ";
1999
2000 EXPECT_TRUE(
2001 matches(ClassString +
2002 "string GetStringByValue();"
2003 "void FunctionTakesString(string s);"
2004 "void run() { FunctionTakesString(GetStringByValue()); }",
2005 materializeTemporaryExpr()));
2006
2007 EXPECT_TRUE(
2008 notMatches(ClassString +
2009 "string* GetStringPointer(); "
2010 "void FunctionTakesStringPtr(string* s);"
2011 "void run() {"
2012 " string* s = GetStringPointer();"
2013 " FunctionTakesStringPtr(GetStringPointer());"
2014 " FunctionTakesStringPtr(s);"
2015 "}",
2016 materializeTemporaryExpr()));
2017
2018 EXPECT_TRUE(
2019 notMatches(ClassString +
2020 "string GetStringByValue();"
2021 "void run() { int k = GetStringByValue().length(); }",
2022 materializeTemporaryExpr()));
2023
2024 EXPECT_TRUE(
2025 notMatches(ClassString +
2026 "string GetStringByValue();"
2027 "void run() { GetStringByValue(); }",
2028 materializeTemporaryExpr()));
2029}
2030
Manuel Klimek04616e42012-07-06 05:48:52 +00002031TEST(ConstructorDeclaration, SimpleCase) {
2032 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002033 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002034 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002035 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002036}
2037
2038TEST(ConstructorDeclaration, IsImplicit) {
2039 // This one doesn't match because the constructor is not added by the
2040 // compiler (it is not needed).
2041 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002042 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002043 // The compiler added the implicit default constructor.
2044 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002045 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002046 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002047 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00002048 // The compiler added an implicit assignment operator.
2049 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
2050 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002051}
2052
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002053TEST(ConstructorDeclaration, IsExplicit) {
2054 EXPECT_TRUE(matches("struct S { explicit S(int); };",
2055 constructorDecl(isExplicit())));
2056 EXPECT_TRUE(notMatches("struct S { S(int); };",
2057 constructorDecl(isExplicit())));
2058}
2059
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002060TEST(ConstructorDeclaration, Kinds) {
2061 EXPECT_TRUE(matches("struct S { S(); };",
2062 constructorDecl(isDefaultConstructor())));
2063 EXPECT_TRUE(notMatches("struct S { S(); };",
2064 constructorDecl(isCopyConstructor())));
2065 EXPECT_TRUE(notMatches("struct S { S(); };",
2066 constructorDecl(isMoveConstructor())));
2067
2068 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
2069 constructorDecl(isDefaultConstructor())));
2070 EXPECT_TRUE(matches("struct S { S(const S&); };",
2071 constructorDecl(isCopyConstructor())));
2072 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
2073 constructorDecl(isMoveConstructor())));
2074
2075 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
2076 constructorDecl(isDefaultConstructor())));
2077 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
2078 constructorDecl(isCopyConstructor())));
2079 EXPECT_TRUE(matches("struct S { S(S&&); };",
2080 constructorDecl(isMoveConstructor())));
2081}
2082
Daniel Jasper1dad1832012-07-10 20:20:19 +00002083TEST(DestructorDeclaration, MatchesVirtualDestructor) {
2084 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002085 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002086}
2087
2088TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002089 EXPECT_TRUE(notMatches("class Foo {};",
2090 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002091}
2092
Manuel Klimek04616e42012-07-06 05:48:52 +00002093TEST(HasAnyConstructorInitializer, SimpleCase) {
2094 EXPECT_TRUE(notMatches(
2095 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002096 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002097 EXPECT_TRUE(matches(
2098 "class Foo {"
2099 " Foo() : foo_() { }"
2100 " int foo_;"
2101 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002102 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002103}
2104
2105TEST(HasAnyConstructorInitializer, ForField) {
2106 static const char Code[] =
2107 "class Baz { };"
2108 "class Foo {"
2109 " Foo() : foo_() { }"
2110 " Baz foo_;"
2111 " Baz bar_;"
2112 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002113 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
2114 forField(hasType(recordDecl(hasName("Baz"))))))));
2115 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002116 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002117 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
2118 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002119}
2120
2121TEST(HasAnyConstructorInitializer, WithInitializer) {
2122 static const char Code[] =
2123 "class Foo {"
2124 " Foo() : foo_(0) { }"
2125 " int foo_;"
2126 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002127 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002128 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002129 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002130 withInitializer(integerLiteral(equals(1)))))));
2131}
2132
2133TEST(HasAnyConstructorInitializer, IsWritten) {
2134 static const char Code[] =
2135 "struct Bar { Bar(){} };"
2136 "class Foo {"
2137 " Foo() : foo_() { }"
2138 " Bar foo_;"
2139 " Bar bar_;"
2140 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002141 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002142 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002143 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002144 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002145 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002146 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2147}
2148
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002149TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
2150 static const char Code[] =
2151 "struct B {};"
2152 "struct D : B {"
2153 " int I;"
2154 " D(int i) : I(i) {}"
2155 "};"
2156 "struct E : B {"
2157 " E() : B() {}"
2158 "};";
2159 EXPECT_TRUE(matches(Code, constructorDecl(allOf(
2160 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2161 hasName("E")))));
2162 EXPECT_TRUE(notMatches(Code, constructorDecl(allOf(
2163 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2164 hasName("D")))));
Aaron Ballmaned455d42015-08-11 20:42:00 +00002165 EXPECT_TRUE(matches(Code, constructorDecl(allOf(
2166 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2167 hasName("D")))));
2168 EXPECT_TRUE(notMatches(Code, constructorDecl(allOf(
2169 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2170 hasName("E")))));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002171}
2172
Manuel Klimek04616e42012-07-06 05:48:52 +00002173TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002174 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002175
2176 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2177 EXPECT_TRUE(
2178 matches("class X { public: X(); }; void x() { new X(); }", New));
2179 EXPECT_TRUE(
2180 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2181 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2182}
2183
2184TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002185 StatementMatcher New = constructExpr(
2186 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002187
2188 EXPECT_TRUE(
2189 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2190 New));
2191 EXPECT_TRUE(
2192 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2193 New));
2194 EXPECT_TRUE(
2195 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2196 New));
2197
Daniel Jasper848cbe12012-09-18 13:09:13 +00002198 StatementMatcher WrongIndex = constructExpr(
2199 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002200 EXPECT_TRUE(
2201 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2202 WrongIndex));
2203}
2204
2205TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002206 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002207
2208 EXPECT_TRUE(
2209 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2210 EXPECT_TRUE(
2211 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2212 New));
2213}
2214
Daniel Jasper1dad1832012-07-10 20:20:19 +00002215TEST(Matcher, DeleteExpression) {
2216 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002217 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002218}
2219
Manuel Klimek04616e42012-07-06 05:48:52 +00002220TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002221 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002222
2223 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2224 EXPECT_TRUE(
2225 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2226 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2227}
2228
2229TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002230 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002231 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2232 // wide string
2233 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2234 // with escaped characters
2235 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2236 // no matching -- though the data type is the same, there is no string literal
2237 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2238}
2239
2240TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002241 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002242 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2243 // wide character
2244 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2245 // wide character, Hex encoded, NOT MATCHED!
2246 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2247 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2248}
2249
2250TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002251 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002252 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2253 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2254 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2255 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2256
2257 // Non-matching cases (character literals, float and double)
2258 EXPECT_TRUE(notMatches("int i = L'a';",
2259 HasIntLiteral)); // this is actually a character
2260 // literal cast to int
2261 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2262 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2263 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2264}
2265
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002266TEST(Matcher, FloatLiterals) {
2267 StatementMatcher HasFloatLiteral = floatLiteral();
2268 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2269 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2270 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2271 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2272 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002273 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2274 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2275 EXPECT_TRUE(
2276 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002277
2278 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002279 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2280 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2281 EXPECT_TRUE(
2282 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002283}
2284
Daniel Jasper5901e472012-10-01 13:40:41 +00002285TEST(Matcher, NullPtrLiteral) {
2286 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2287}
2288
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002289TEST(Matcher, GNUNullExpr) {
2290 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2291}
2292
Daniel Jasper87c3d362012-09-20 14:12:57 +00002293TEST(Matcher, AsmStatement) {
2294 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2295}
2296
Manuel Klimek04616e42012-07-06 05:48:52 +00002297TEST(Matcher, Conditions) {
2298 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2299
2300 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2301 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2302 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2303 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2304 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2305}
2306
Manuel Klimek909b5c942014-05-27 10:04:12 +00002307TEST(IfStmt, ChildTraversalMatchers) {
2308 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2309 ifStmt(hasThen(boolLiteral(equals(true))))));
2310 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2311 ifStmt(hasThen(boolLiteral(equals(true))))));
2312 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2313 ifStmt(hasElse(boolLiteral(equals(true))))));
2314 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2315 ifStmt(hasElse(boolLiteral(equals(true))))));
2316}
2317
Manuel Klimek04616e42012-07-06 05:48:52 +00002318TEST(MatchBinaryOperator, HasOperatorName) {
2319 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2320
2321 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2322 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2323}
2324
2325TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2326 StatementMatcher OperatorTrueFalse =
2327 binaryOperator(hasLHS(boolLiteral(equals(true))),
2328 hasRHS(boolLiteral(equals(false))));
2329
2330 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2331 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2332 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2333}
2334
2335TEST(MatchBinaryOperator, HasEitherOperand) {
2336 StatementMatcher HasOperand =
2337 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2338
2339 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2340 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2341 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2342}
2343
2344TEST(Matcher, BinaryOperatorTypes) {
2345 // Integration test that verifies the AST provides all binary operators in
2346 // a way we expect.
2347 // FIXME: Operator ','
2348 EXPECT_TRUE(
2349 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2350 EXPECT_TRUE(
2351 matches("bool b; bool c = (b = true);",
2352 binaryOperator(hasOperatorName("="))));
2353 EXPECT_TRUE(
2354 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2355 EXPECT_TRUE(
2356 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2357 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2358 EXPECT_TRUE(
2359 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2360 EXPECT_TRUE(
2361 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2362 EXPECT_TRUE(
2363 matches("int i = 1; int j = (i <<= 2);",
2364 binaryOperator(hasOperatorName("<<="))));
2365 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2366 EXPECT_TRUE(
2367 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2368 EXPECT_TRUE(
2369 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2370 EXPECT_TRUE(
2371 matches("int i = 1; int j = (i >>= 2);",
2372 binaryOperator(hasOperatorName(">>="))));
2373 EXPECT_TRUE(
2374 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2375 EXPECT_TRUE(
2376 matches("int i = 42; int j = (i ^= 42);",
2377 binaryOperator(hasOperatorName("^="))));
2378 EXPECT_TRUE(
2379 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2380 EXPECT_TRUE(
2381 matches("int i = 42; int j = (i %= 42);",
2382 binaryOperator(hasOperatorName("%="))));
2383 EXPECT_TRUE(
2384 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2385 EXPECT_TRUE(
2386 matches("bool b = true && false;",
2387 binaryOperator(hasOperatorName("&&"))));
2388 EXPECT_TRUE(
2389 matches("bool b = true; bool c = (b &= false);",
2390 binaryOperator(hasOperatorName("&="))));
2391 EXPECT_TRUE(
2392 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2393 EXPECT_TRUE(
2394 matches("bool b = true || false;",
2395 binaryOperator(hasOperatorName("||"))));
2396 EXPECT_TRUE(
2397 matches("bool b = true; bool c = (b |= false);",
2398 binaryOperator(hasOperatorName("|="))));
2399 EXPECT_TRUE(
2400 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2401 EXPECT_TRUE(
2402 matches("int i = 42; int j = (i *= 23);",
2403 binaryOperator(hasOperatorName("*="))));
2404 EXPECT_TRUE(
2405 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2406 EXPECT_TRUE(
2407 matches("int i = 42; int j = (i /= 23);",
2408 binaryOperator(hasOperatorName("/="))));
2409 EXPECT_TRUE(
2410 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2411 EXPECT_TRUE(
2412 matches("int i = 42; int j = (i += 23);",
2413 binaryOperator(hasOperatorName("+="))));
2414 EXPECT_TRUE(
2415 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2416 EXPECT_TRUE(
2417 matches("int i = 42; int j = (i -= 23);",
2418 binaryOperator(hasOperatorName("-="))));
2419 EXPECT_TRUE(
2420 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2421 binaryOperator(hasOperatorName("->*"))));
2422 EXPECT_TRUE(
2423 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2424 binaryOperator(hasOperatorName(".*"))));
2425
2426 // Member expressions as operators are not supported in matches.
2427 EXPECT_TRUE(
2428 notMatches("struct A { void x(A *a) { a->x(this); } };",
2429 binaryOperator(hasOperatorName("->"))));
2430
2431 // Initializer assignments are not represented as operator equals.
2432 EXPECT_TRUE(
2433 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2434
2435 // Array indexing is not represented as operator.
2436 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2437
2438 // Overloaded operators do not match at all.
2439 EXPECT_TRUE(notMatches(
2440 "struct A { bool operator&&(const A &a) const { return false; } };"
2441 "void x() { A a, b; a && b; }",
2442 binaryOperator()));
2443}
2444
2445TEST(MatchUnaryOperator, HasOperatorName) {
2446 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2447
2448 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2449 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2450}
2451
2452TEST(MatchUnaryOperator, HasUnaryOperand) {
2453 StatementMatcher OperatorOnFalse =
2454 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2455
2456 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2457 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2458}
2459
2460TEST(Matcher, UnaryOperatorTypes) {
2461 // Integration test that verifies the AST provides all unary operators in
2462 // a way we expect.
2463 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2464 EXPECT_TRUE(
2465 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2466 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2467 EXPECT_TRUE(
2468 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2469 EXPECT_TRUE(
2470 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2471 EXPECT_TRUE(
2472 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2473 EXPECT_TRUE(
2474 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2475 EXPECT_TRUE(
2476 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2477 EXPECT_TRUE(
2478 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2479 EXPECT_TRUE(
2480 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2481
2482 // We don't match conversion operators.
2483 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2484
2485 // Function calls are not represented as operator.
2486 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2487
2488 // Overloaded operators do not match at all.
2489 // FIXME: We probably want to add that.
2490 EXPECT_TRUE(notMatches(
2491 "struct A { bool operator!() const { return false; } };"
2492 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2493}
2494
2495TEST(Matcher, ConditionalOperator) {
2496 StatementMatcher Conditional = conditionalOperator(
2497 hasCondition(boolLiteral(equals(true))),
2498 hasTrueExpression(boolLiteral(equals(false))));
2499
2500 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2501 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2502 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2503
2504 StatementMatcher ConditionalFalse = conditionalOperator(
2505 hasFalseExpression(boolLiteral(equals(false))));
2506
2507 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2508 EXPECT_TRUE(
2509 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2510}
2511
Daniel Jasper1dad1832012-07-10 20:20:19 +00002512TEST(ArraySubscriptMatchers, ArraySubscripts) {
2513 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2514 arraySubscriptExpr()));
2515 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2516 arraySubscriptExpr()));
2517}
2518
2519TEST(ArraySubscriptMatchers, ArrayIndex) {
2520 EXPECT_TRUE(matches(
2521 "int i[2]; void f() { i[1] = 1; }",
2522 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2523 EXPECT_TRUE(matches(
2524 "int i[2]; void f() { 1[i] = 1; }",
2525 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2526 EXPECT_TRUE(notMatches(
2527 "int i[2]; void f() { i[1] = 1; }",
2528 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2529}
2530
2531TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2532 EXPECT_TRUE(matches(
2533 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002534 arraySubscriptExpr(hasBase(implicitCastExpr(
2535 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002536}
2537
Manuel Klimek04616e42012-07-06 05:48:52 +00002538TEST(Matcher, HasNameSupportsNamespaces) {
2539 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002540 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002541 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002542 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002543 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002544 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002545 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002546 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002547 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002548 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002549 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002550 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002551 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002552 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002553 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002554 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002555 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002556 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002557 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002558 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002559 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002560 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002561 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002562 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002563}
2564
2565TEST(Matcher, HasNameSupportsOuterClasses) {
2566 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002567 matches("class A { class B { class C; }; };",
2568 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002569 EXPECT_TRUE(
2570 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002571 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002572 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002573 matches("class A { class B { class C; }; };",
2574 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002575 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002576 matches("class A { class B { class C; }; };",
2577 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002578 EXPECT_TRUE(
2579 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002580 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002581 EXPECT_TRUE(
2582 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002583 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002584 EXPECT_TRUE(
2585 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002586 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002587 EXPECT_TRUE(
2588 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002589 recordDecl(hasName("::C"))));
2590 EXPECT_TRUE(
2591 notMatches("class A { class B { class C; }; };",
2592 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002593 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002594 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002595 EXPECT_TRUE(
2596 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002597 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002598}
2599
2600TEST(Matcher, IsDefinition) {
2601 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002602 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002603 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2604 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2605
2606 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002607 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002608 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2609 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2610
2611 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002612 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002613 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2614 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2615}
2616
2617TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002618 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002619 ofClass(hasName("X")))));
2620
2621 EXPECT_TRUE(
2622 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2623 EXPECT_TRUE(
2624 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2625 Constructor));
2626 EXPECT_TRUE(
2627 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2628 Constructor));
2629}
2630
2631TEST(Matcher, VisitsTemplateInstantiations) {
2632 EXPECT_TRUE(matches(
2633 "class A { public: void x(); };"
2634 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002635 "void f() { B<A> b; b.y(); }",
2636 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002637
2638 EXPECT_TRUE(matches(
2639 "class A { public: void x(); };"
2640 "class C {"
2641 " public:"
2642 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2643 "};"
2644 "void f() {"
2645 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002646 "}",
2647 recordDecl(hasName("C"),
2648 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002649}
2650
Daniel Jasper1dad1832012-07-10 20:20:19 +00002651TEST(Matcher, HandlesNullQualTypes) {
2652 // FIXME: Add a Type matcher so we can replace uses of this
2653 // variable with Type(True())
2654 const TypeMatcher AnyType = anything();
2655
2656 // We don't really care whether this matcher succeeds; we're testing that
2657 // it completes without crashing.
2658 EXPECT_TRUE(matches(
2659 "struct A { };"
2660 "template <typename T>"
2661 "void f(T t) {"
2662 " T local_t(t /* this becomes a null QualType in the AST */);"
2663 "}"
2664 "void g() {"
2665 " f(0);"
2666 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002667 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002668 anyOf(
2669 TypeMatcher(hasDeclaration(anything())),
2670 pointsTo(AnyType),
2671 references(AnyType)
2672 // Other QualType matchers should go here.
2673 ))))));
2674}
2675
Manuel Klimek04616e42012-07-06 05:48:52 +00002676// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002677AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002678 // Make sure all special variables are used: node, match_finder,
2679 // bound_nodes_builder, and the parameter named 'AMatcher'.
2680 return AMatcher.matches(Node, Finder, Builder);
2681}
2682
2683TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002684 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002685
2686 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002687 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002688
2689 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002690 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002691
2692 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002693 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002694}
2695
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002696AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2697 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2698 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002699 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002700 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002701 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2702 ASTMatchFinder::BK_First);
2703}
2704
2705TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002706 DeclarationMatcher HasClassB =
2707 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002708
2709 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002710 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002711
2712 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002713 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002714
2715 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002716 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002717
2718 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002719 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002720
2721 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2722}
2723
2724TEST(For, FindsForLoops) {
2725 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2726 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002727 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2728 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002729 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002730}
2731
Daniel Jasper4e566c42012-07-12 08:50:38 +00002732TEST(For, ForLoopInternals) {
2733 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2734 forStmt(hasCondition(anything()))));
2735 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2736 forStmt(hasLoopInit(anything()))));
2737}
2738
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002739TEST(For, ForRangeLoopInternals) {
2740 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2741 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002742 EXPECT_TRUE(matches(
2743 "void f(){ int a[] {1, 2}; for (int i : a); }",
2744 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002745}
2746
Daniel Jasper4e566c42012-07-12 08:50:38 +00002747TEST(For, NegativeForLoopInternals) {
2748 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002749 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002750 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2751 forStmt(hasLoopInit(anything()))));
2752}
2753
Manuel Klimek04616e42012-07-06 05:48:52 +00002754TEST(For, ReportsNoFalsePositives) {
2755 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2756 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2757}
2758
2759TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002760 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2761 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2762 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002763}
2764
2765TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2766 // It's not a compound statement just because there's "{}" in the source
2767 // text. This is an AST search, not grep.
2768 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002769 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002770 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002771 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002772}
2773
Daniel Jasper4e566c42012-07-12 08:50:38 +00002774TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002775 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002776 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002777 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002778 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002779 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002780 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002781 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002782 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002783 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2784 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002785}
2786
2787TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2788 // The simplest case: every compound statement is in a function
2789 // definition, and the function body itself must be a compound
2790 // statement.
2791 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002792 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002793}
2794
2795TEST(HasAnySubstatement, IsNotRecursive) {
2796 // It's really "has any immediate substatement".
2797 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002798 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002799}
2800
2801TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2802 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002803 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002804}
2805
2806TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2807 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002808 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002809}
2810
2811TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2812 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002813 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002814 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002815 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002816}
2817
2818TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2819 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002820 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002821 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002822 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002823 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002824 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002825}
2826
2827TEST(StatementCountIs, WorksWithMultipleStatements) {
2828 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002829 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002830}
2831
2832TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2833 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002834 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002835 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002836 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002837 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002838 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002839 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002840 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002841}
2842
2843TEST(Member, WorksInSimplestCase) {
2844 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002845 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002846}
2847
2848TEST(Member, DoesNotMatchTheBaseExpression) {
2849 // Don't pick out the wrong part of the member expression, this should
2850 // be checking the member (name) only.
2851 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002852 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002853}
2854
2855TEST(Member, MatchesInMemberFunctionCall) {
2856 EXPECT_TRUE(matches("void f() {"
2857 " struct { void first() {}; } s;"
2858 " s.first();"
2859 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002860 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002861}
2862
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002863TEST(Member, MatchesMember) {
2864 EXPECT_TRUE(matches(
2865 "struct A { int i; }; void f() { A a; a.i = 2; }",
2866 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2867 EXPECT_TRUE(notMatches(
2868 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2869 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2870}
2871
Daniel Jasper639522c2013-02-25 12:02:08 +00002872TEST(Member, UnderstandsAccess) {
2873 EXPECT_TRUE(matches(
2874 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2875 EXPECT_TRUE(notMatches(
2876 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2877 EXPECT_TRUE(notMatches(
2878 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2879
2880 EXPECT_TRUE(notMatches(
2881 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2882 EXPECT_TRUE(notMatches(
2883 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2884 EXPECT_TRUE(matches(
2885 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2886
2887 EXPECT_TRUE(notMatches(
2888 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2889 EXPECT_TRUE(matches("class A { protected: int i; };",
2890 fieldDecl(isProtected(), hasName("i"))));
2891 EXPECT_TRUE(notMatches(
2892 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2893
2894 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2895 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2896 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2897 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2898}
2899
Dmitri Gribenko06963042012-08-18 00:29:27 +00002900TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002901 // Fails in C++11 mode
2902 EXPECT_TRUE(matchesConditionally(
2903 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2904 "class X { void *operator new(std::size_t); };",
2905 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002906
2907 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002908 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002909
Daniel Jasper5901e472012-10-01 13:40:41 +00002910 // Fails in C++11 mode
2911 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002912 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2913 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002914 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002915}
2916
Manuel Klimek04616e42012-07-06 05:48:52 +00002917TEST(HasObjectExpression, DoesNotMatchMember) {
2918 EXPECT_TRUE(notMatches(
2919 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002920 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002921}
2922
2923TEST(HasObjectExpression, MatchesBaseOfVariable) {
2924 EXPECT_TRUE(matches(
2925 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002926 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002927 EXPECT_TRUE(matches(
2928 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002929 memberExpr(hasObjectExpression(
2930 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002931}
2932
2933TEST(HasObjectExpression,
2934 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2935 EXPECT_TRUE(matches(
2936 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002937 memberExpr(hasObjectExpression(
2938 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002939 EXPECT_TRUE(matches(
2940 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002941 memberExpr(hasObjectExpression(
2942 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002943}
2944
2945TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002946 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2947 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2948 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2949 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002950}
2951
2952TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002953 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002954}
2955
2956TEST(IsConstQualified, MatchesConstInt) {
2957 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002958 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002959}
2960
2961TEST(IsConstQualified, MatchesConstPointer) {
2962 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002963 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002964}
2965
2966TEST(IsConstQualified, MatchesThroughTypedef) {
2967 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002968 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002969 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002970 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002971}
2972
2973TEST(IsConstQualified, DoesNotMatchInappropriately) {
2974 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002975 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002976 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002977 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002978}
2979
Sam Panzer80c13772012-08-16 16:58:10 +00002980TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002981 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2982 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2983 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2984 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002985}
2986TEST(CastExpression, MatchesImplicitCasts) {
2987 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002988 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002989 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002990 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002991}
2992
2993TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002994 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2995 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2996 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2997 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002998}
2999
Manuel Klimek04616e42012-07-06 05:48:52 +00003000TEST(ReinterpretCast, MatchesSimpleCase) {
3001 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003002 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003003}
3004
3005TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003006 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003007 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003008 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003009 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003010 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003011 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3012 "B b;"
3013 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003014 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003015}
3016
3017TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003018 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003019 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003020 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003021}
3022
3023TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003024 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003025 EXPECT_TRUE(
3026 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003027 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003028 EXPECT_TRUE(
3029 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003030 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003031}
3032
3033TEST(DynamicCast, MatchesSimpleCase) {
3034 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
3035 "B b;"
3036 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003037 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003038}
3039
3040TEST(StaticCast, MatchesSimpleCase) {
3041 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003042 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003043}
3044
3045TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003046 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003047 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003048 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003049 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003050 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003051 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3052 "B b;"
3053 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003054 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003055}
3056
Daniel Jasper417f7762012-09-18 13:36:17 +00003057TEST(CStyleCast, MatchesSimpleCase) {
3058 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
3059}
3060
3061TEST(CStyleCast, DoesNotMatchOtherCasts) {
3062 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
3063 "char q, *r = const_cast<char*>(&q);"
3064 "void* s = reinterpret_cast<char*>(&s);"
3065 "struct B { virtual ~B() {} }; struct D : B {};"
3066 "B b;"
3067 "D* t = dynamic_cast<D*>(&b);",
3068 cStyleCastExpr()));
3069}
3070
Manuel Klimek04616e42012-07-06 05:48:52 +00003071TEST(HasDestinationType, MatchesSimpleCase) {
3072 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003073 staticCastExpr(hasDestinationType(
3074 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003075}
3076
Sam Panzer80c13772012-08-16 16:58:10 +00003077TEST(HasImplicitDestinationType, MatchesSimpleCase) {
3078 // This test creates an implicit const cast.
3079 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003080 implicitCastExpr(
3081 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003082 // This test creates an implicit array-to-pointer cast.
3083 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003084 implicitCastExpr(hasImplicitDestinationType(
3085 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003086}
3087
3088TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
3089 // This test creates an implicit cast from int to char.
3090 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003091 implicitCastExpr(hasImplicitDestinationType(
3092 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003093 // This test creates an implicit array-to-pointer cast.
3094 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003095 implicitCastExpr(hasImplicitDestinationType(
3096 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003097}
3098
3099TEST(ImplicitCast, MatchesSimpleCase) {
3100 // This test creates an implicit const cast.
3101 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003102 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003103 // This test creates an implicit cast from int to char.
3104 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003105 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003106 // This test creates an implicit array-to-pointer cast.
3107 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003108 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003109}
3110
3111TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003112 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00003113 // are present, and that it ignores explicit and paren casts.
3114
3115 // These two test cases have no casts.
3116 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003117 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003118 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003119 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003120
3121 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003122 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003123 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003124 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003125
3126 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003127 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003128}
3129
3130TEST(IgnoringImpCasts, MatchesImpCasts) {
3131 // This test checks that ignoringImpCasts matches when implicit casts are
3132 // present and its inner matcher alone does not match.
3133 // Note that this test creates an implicit const cast.
3134 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003135 varDecl(hasInitializer(ignoringImpCasts(
3136 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003137 // This test creates an implict cast from int to char.
3138 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003139 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003140 integerLiteral(equals(0)))))));
3141}
3142
3143TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3144 // These tests verify that ignoringImpCasts does not match if the inner
3145 // matcher does not match.
3146 // Note that the first test creates an implicit const cast.
3147 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003148 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003149 unless(anything()))))));
3150 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003151 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003152 unless(anything()))))));
3153
3154 // These tests verify that ignoringImplictCasts does not look through explicit
3155 // casts or parentheses.
3156 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003157 varDecl(hasInitializer(ignoringImpCasts(
3158 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003159 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003160 varDecl(hasInitializer(ignoringImpCasts(
3161 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003162 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003163 varDecl(hasInitializer(ignoringImpCasts(
3164 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003165 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003166 varDecl(hasInitializer(ignoringImpCasts(
3167 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003168}
3169
3170TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3171 // This test verifies that expressions that do not have implicit casts
3172 // still match the inner matcher.
3173 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003174 varDecl(hasInitializer(ignoringImpCasts(
3175 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003176}
3177
3178TEST(IgnoringParenCasts, MatchesParenCasts) {
3179 // This test checks that ignoringParenCasts matches when parentheses and/or
3180 // casts are present and its inner matcher alone does not match.
3181 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003182 varDecl(hasInitializer(ignoringParenCasts(
3183 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003184 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003185 varDecl(hasInitializer(ignoringParenCasts(
3186 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003187
3188 // This test creates an implict cast from int to char in addition to the
3189 // parentheses.
3190 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003191 varDecl(hasInitializer(ignoringParenCasts(
3192 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003193
3194 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003195 varDecl(hasInitializer(ignoringParenCasts(
3196 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003197 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003198 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003199 integerLiteral(equals(0)))))));
3200}
3201
3202TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3203 // This test verifies that expressions that do not have any casts still match.
3204 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003205 varDecl(hasInitializer(ignoringParenCasts(
3206 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003207}
3208
3209TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3210 // These tests verify that ignoringImpCasts does not match if the inner
3211 // matcher does not match.
3212 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003213 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003214 unless(anything()))))));
3215
3216 // This test creates an implicit cast from int to char in addition to the
3217 // parentheses.
3218 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003219 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003220 unless(anything()))))));
3221
3222 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003223 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003224 unless(anything()))))));
3225}
3226
3227TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3228 // This test checks that ignoringParenAndImpCasts matches when
3229 // parentheses and/or implicit casts are present and its inner matcher alone
3230 // does not match.
3231 // Note that this test creates an implicit const cast.
3232 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003233 varDecl(hasInitializer(ignoringParenImpCasts(
3234 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003235 // This test creates an implicit cast from int to char.
3236 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003237 varDecl(hasInitializer(ignoringParenImpCasts(
3238 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003239}
3240
3241TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3242 // This test verifies that expressions that do not have parentheses or
3243 // implicit casts still match.
3244 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003245 varDecl(hasInitializer(ignoringParenImpCasts(
3246 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003247 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003248 varDecl(hasInitializer(ignoringParenImpCasts(
3249 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003250}
3251
3252TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3253 // These tests verify that ignoringParenImpCasts does not match if
3254 // the inner matcher does not match.
3255 // This test creates an implicit cast.
3256 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003257 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003258 unless(anything()))))));
3259 // These tests verify that ignoringParenAndImplictCasts does not look
3260 // through explicit casts.
3261 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003262 varDecl(hasInitializer(ignoringParenImpCasts(
3263 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003264 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003265 varDecl(hasInitializer(ignoringParenImpCasts(
3266 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003267 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003268 varDecl(hasInitializer(ignoringParenImpCasts(
3269 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003270}
3271
Manuel Klimeke9235692012-07-25 10:02:02 +00003272TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003273 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3274 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003275 implicitCastExpr(
3276 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003277}
3278
Manuel Klimeke9235692012-07-25 10:02:02 +00003279TEST(HasSourceExpression, MatchesExplicitCasts) {
3280 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003281 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003282 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003283 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003284}
3285
Manuel Klimek04616e42012-07-06 05:48:52 +00003286TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003287 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003288}
3289
3290TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003291 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003292}
3293
3294TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003295 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003296}
3297
3298TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003299 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003300}
3301
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003302TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3303 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3304 "const Foo f = Foo();",
3305 varDecl(hasInitializer(exprWithCleanups()))));
3306 EXPECT_FALSE(matches("struct Foo { };"
3307 "const Foo f = Foo();",
3308 varDecl(hasInitializer(exprWithCleanups()))));
3309}
3310
Daniel Jasper1dad1832012-07-10 20:20:19 +00003311TEST(InitListExpression, MatchesInitListExpression) {
3312 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3313 initListExpr(hasType(asString("int [2]")))));
3314 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003315 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003316 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3317 "void f();"
3318 "S s[1] = { &f };",
3319 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003320 EXPECT_TRUE(
3321 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003322}
3323
3324TEST(UsingDeclaration, MatchesUsingDeclarations) {
3325 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3326 usingDecl()));
3327}
3328
3329TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3330 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3331 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3332}
3333
3334TEST(UsingDeclaration, MatchesSpecificTarget) {
3335 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3336 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003337 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003338 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3339 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003340 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003341}
3342
3343TEST(UsingDeclaration, ThroughUsingDeclaration) {
3344 EXPECT_TRUE(matches(
3345 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003346 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003347 EXPECT_TRUE(notMatches(
3348 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003349 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003350}
3351
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003352TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3353 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3354 usingDirectiveDecl()));
3355 EXPECT_FALSE(
3356 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3357}
3358
Sam Panzerd624bfb2012-08-16 17:20:59 +00003359TEST(SingleDecl, IsSingleDecl) {
3360 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003361 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003362 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3363 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3364 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3365 SingleDeclStmt));
3366}
3367
3368TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003369 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003370
3371 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003372 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003373 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003374 declStmt(containsDeclaration(0, MatchesInit),
3375 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003376 unsigned WrongIndex = 42;
3377 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003378 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003379 MatchesInit))));
3380}
3381
3382TEST(DeclCount, DeclCountIsCorrect) {
3383 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003384 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003385 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003386 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003387 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003388 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003389}
3390
Manuel Klimek04616e42012-07-06 05:48:52 +00003391TEST(While, MatchesWhileLoops) {
3392 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3393 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3394 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3395}
3396
3397TEST(Do, MatchesDoLoops) {
3398 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3399 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3400}
3401
3402TEST(Do, DoesNotMatchWhileLoops) {
3403 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3404}
3405
3406TEST(SwitchCase, MatchesCase) {
3407 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3408 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3409 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3410 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3411}
3412
Daniel Jasper87c3d362012-09-20 14:12:57 +00003413TEST(SwitchCase, MatchesSwitch) {
3414 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3415 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3416 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3417 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3418}
3419
Peter Collingbourne3154a102013-05-10 11:52:02 +00003420TEST(SwitchCase, MatchesEachCase) {
3421 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3422 switchStmt(forEachSwitchCase(caseStmt()))));
3423 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3424 switchStmt(forEachSwitchCase(caseStmt()))));
3425 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3426 switchStmt(forEachSwitchCase(caseStmt()))));
3427 EXPECT_TRUE(notMatches(
3428 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3429 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3430 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3431 switchStmt(forEachSwitchCase(
3432 caseStmt(hasCaseConstant(integerLiteral()))))));
3433 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3434 switchStmt(forEachSwitchCase(
3435 caseStmt(hasCaseConstant(integerLiteral()))))));
3436 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3437 switchStmt(forEachSwitchCase(
3438 caseStmt(hasCaseConstant(integerLiteral()))))));
3439 EXPECT_TRUE(matchAndVerifyResultTrue(
3440 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3441 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3442 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3443}
3444
Manuel Klimekba46fc02013-07-19 11:50:54 +00003445TEST(ForEachConstructorInitializer, MatchesInitializers) {
3446 EXPECT_TRUE(matches(
3447 "struct X { X() : i(42), j(42) {} int i, j; };",
3448 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3449}
3450
Daniel Jasper87c3d362012-09-20 14:12:57 +00003451TEST(ExceptionHandling, SimpleCases) {
3452 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3453 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3454 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3455 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3456 throwExpr()));
3457 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3458 throwExpr()));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003459 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
3460 catchStmt(isCatchAll())));
3461 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
3462 catchStmt(isCatchAll())));
Aaron Ballman39918462015-07-15 17:11:21 +00003463 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3464 varDecl(isExceptionVariable())));
3465 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3466 varDecl(isExceptionVariable())));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003467}
3468
Manuel Klimek04616e42012-07-06 05:48:52 +00003469TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3470 EXPECT_TRUE(notMatches(
3471 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003472 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003473 EXPECT_TRUE(notMatches(
3474 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003475 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003476}
3477
3478TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3479 EXPECT_TRUE(matches(
3480 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003481 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003482}
3483
3484TEST(ForEach, BindsOneNode) {
3485 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003486 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003487 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003488}
3489
3490TEST(ForEach, BindsMultipleNodes) {
3491 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003492 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003493 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003494}
3495
3496TEST(ForEach, BindsRecursiveCombinations) {
3497 EXPECT_TRUE(matchAndVerifyResultTrue(
3498 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003499 recordDecl(hasName("C"),
3500 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003501 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003502}
3503
3504TEST(ForEachDescendant, BindsOneNode) {
3505 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003506 recordDecl(hasName("C"),
3507 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003508 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003509}
3510
Daniel Jasper94a56852012-11-16 18:39:22 +00003511TEST(ForEachDescendant, NestedForEachDescendant) {
3512 DeclarationMatcher m = recordDecl(
3513 isDefinition(), decl().bind("x"), hasName("C"));
3514 EXPECT_TRUE(matchAndVerifyResultTrue(
3515 "class A { class B { class C {}; }; };",
3516 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3517 new VerifyIdIsBoundTo<Decl>("x", "C")));
3518
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003519 // Check that a partial match of 'm' that binds 'x' in the
3520 // first part of anyOf(m, anything()) will not overwrite the
3521 // binding created by the earlier binding in the hasDescendant.
3522 EXPECT_TRUE(matchAndVerifyResultTrue(
3523 "class A { class B { class C {}; }; };",
3524 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3525 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003526}
3527
Manuel Klimek04616e42012-07-06 05:48:52 +00003528TEST(ForEachDescendant, BindsMultipleNodes) {
3529 EXPECT_TRUE(matchAndVerifyResultTrue(
3530 "class C { class D { int x; int y; }; "
3531 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003532 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003533 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003534}
3535
3536TEST(ForEachDescendant, BindsRecursiveCombinations) {
3537 EXPECT_TRUE(matchAndVerifyResultTrue(
3538 "class C { class D { "
3539 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003540 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3541 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003542 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003543}
3544
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003545TEST(ForEachDescendant, BindsCombinations) {
3546 EXPECT_TRUE(matchAndVerifyResultTrue(
3547 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3548 "(true) {} }",
3549 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3550 forEachDescendant(whileStmt().bind("while"))),
3551 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3552}
3553
3554TEST(Has, DoesNotDeleteBindings) {
3555 EXPECT_TRUE(matchAndVerifyResultTrue(
3556 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3557 new VerifyIdIsBoundTo<Decl>("x", 1)));
3558}
3559
3560TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3561 // Those matchers cover all the cases where an inner matcher is called
3562 // and there is not a 1:1 relationship between the match of the outer
3563 // matcher and the match of the inner matcher.
3564 // The pattern to look for is:
3565 // ... return InnerMatcher.matches(...); ...
3566 // In which case no special handling is needed.
3567 //
3568 // On the other hand, if there are multiple alternative matches
3569 // (for example forEach*) or matches might be discarded (for example has*)
3570 // the implementation must make sure that the discarded matches do not
3571 // affect the bindings.
3572 // When new such matchers are added, add a test here that:
3573 // - matches a simple node, and binds it as the first thing in the matcher:
3574 // recordDecl(decl().bind("x"), hasName("X")))
3575 // - uses the matcher under test afterwards in a way that not the first
3576 // alternative is matched; for anyOf, that means the first branch
3577 // would need to return false; for hasAncestor, it means that not
3578 // the direct parent matches the inner matcher.
3579
3580 EXPECT_TRUE(matchAndVerifyResultTrue(
3581 "class X { int y; };",
3582 recordDecl(
3583 recordDecl().bind("x"), hasName("::X"),
3584 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3585 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3586 EXPECT_TRUE(matchAndVerifyResultTrue(
3587 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3588 anyOf(unless(anything()), anything())),
3589 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3590 EXPECT_TRUE(matchAndVerifyResultTrue(
3591 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3592 classTemplateSpecializationDecl(
3593 decl().bind("x"),
3594 hasAnyTemplateArgument(refersToType(asString("int")))),
3595 new VerifyIdIsBoundTo<Decl>("x", 1)));
3596 EXPECT_TRUE(matchAndVerifyResultTrue(
3597 "class X { void f(); void g(); };",
3598 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3599 new VerifyIdIsBoundTo<Decl>("x", 1)));
3600 EXPECT_TRUE(matchAndVerifyResultTrue(
3601 "class X { X() : a(1), b(2) {} double a; int b; };",
3602 recordDecl(decl().bind("x"),
3603 has(constructorDecl(
3604 hasAnyConstructorInitializer(forField(hasName("b")))))),
3605 new VerifyIdIsBoundTo<Decl>("x", 1)));
3606 EXPECT_TRUE(matchAndVerifyResultTrue(
3607 "void x(int, int) { x(0, 42); }",
3608 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3609 new VerifyIdIsBoundTo<Expr>("x", 1)));
3610 EXPECT_TRUE(matchAndVerifyResultTrue(
3611 "void x(int, int y) {}",
3612 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3613 new VerifyIdIsBoundTo<Decl>("x", 1)));
3614 EXPECT_TRUE(matchAndVerifyResultTrue(
3615 "void x() { return; if (true) {} }",
3616 functionDecl(decl().bind("x"),
3617 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3618 new VerifyIdIsBoundTo<Decl>("x", 1)));
3619 EXPECT_TRUE(matchAndVerifyResultTrue(
3620 "namespace X { void b(int); void b(); }"
3621 "using X::b;",
3622 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3623 functionDecl(parameterCountIs(1))))),
3624 new VerifyIdIsBoundTo<Decl>("x", 1)));
3625 EXPECT_TRUE(matchAndVerifyResultTrue(
3626 "class A{}; class B{}; class C : B, A {};",
3627 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3628 new VerifyIdIsBoundTo<Decl>("x", 1)));
3629 EXPECT_TRUE(matchAndVerifyResultTrue(
3630 "class A{}; typedef A B; typedef A C; typedef A D;"
3631 "class E : A {};",
3632 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3633 new VerifyIdIsBoundTo<Decl>("x", 1)));
3634 EXPECT_TRUE(matchAndVerifyResultTrue(
3635 "class A { class B { void f() {} }; };",
3636 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3637 new VerifyIdIsBoundTo<Decl>("x", 1)));
3638 EXPECT_TRUE(matchAndVerifyResultTrue(
3639 "template <typename T> struct A { struct B {"
3640 " void f() { if(true) {} }"
3641 "}; };"
3642 "void t() { A<int>::B b; b.f(); }",
3643 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3644 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3645 EXPECT_TRUE(matchAndVerifyResultTrue(
3646 "class A {};",
3647 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3648 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003649 EXPECT_TRUE(matchAndVerifyResultTrue(
3650 "class A { A() : s(), i(42) {} const char *s; int i; };",
3651 constructorDecl(hasName("::A::A"), decl().bind("x"),
3652 forEachConstructorInitializer(forField(hasName("i")))),
3653 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003654}
3655
Daniel Jasper33806cd2012-11-11 22:14:55 +00003656TEST(ForEachDescendant, BindsCorrectNodes) {
3657 EXPECT_TRUE(matchAndVerifyResultTrue(
3658 "class C { void f(); int i; };",
3659 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3660 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3661 EXPECT_TRUE(matchAndVerifyResultTrue(
3662 "class C { void f() {} int i; };",
3663 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3664 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3665}
3666
Manuel Klimekabf43712013-02-04 10:59:20 +00003667TEST(FindAll, BindsNodeOnMatch) {
3668 EXPECT_TRUE(matchAndVerifyResultTrue(
3669 "class A {};",
3670 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3671 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3672}
3673
3674TEST(FindAll, BindsDescendantNodeOnMatch) {
3675 EXPECT_TRUE(matchAndVerifyResultTrue(
3676 "class A { int a; int b; };",
3677 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3678 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3679}
3680
3681TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3682 EXPECT_TRUE(matchAndVerifyResultTrue(
3683 "class A { int a; int b; };",
3684 recordDecl(hasName("::A"),
3685 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3686 fieldDecl().bind("v"))))),
3687 new VerifyIdIsBoundTo<Decl>("v", 3)));
3688
3689 EXPECT_TRUE(matchAndVerifyResultTrue(
3690 "class A { class B {}; class C {}; };",
3691 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3692 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3693}
3694
Manuel Klimek88b95872013-02-04 09:42:38 +00003695TEST(EachOf, TriggersForEachMatch) {
3696 EXPECT_TRUE(matchAndVerifyResultTrue(
3697 "class A { int a; int b; };",
3698 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3699 has(fieldDecl(hasName("b")).bind("v")))),
3700 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3701}
3702
3703TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3704 EXPECT_TRUE(matchAndVerifyResultTrue(
3705 "class A { int a; int c; };",
3706 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3707 has(fieldDecl(hasName("b")).bind("v")))),
3708 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3709 EXPECT_TRUE(matchAndVerifyResultTrue(
3710 "class A { int c; int b; };",
3711 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3712 has(fieldDecl(hasName("b")).bind("v")))),
3713 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3714 EXPECT_TRUE(notMatches(
3715 "class A { int c; int d; };",
3716 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3717 has(fieldDecl(hasName("b")).bind("v"))))));
3718}
Manuel Klimek04616e42012-07-06 05:48:52 +00003719
3720TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3721 // Make sure that we can both match the class by name (::X) and by the type
3722 // the template was instantiated with (via a field).
3723
3724 EXPECT_TRUE(matches(
3725 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003726 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003727
3728 EXPECT_TRUE(matches(
3729 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003730 recordDecl(isTemplateInstantiation(), hasDescendant(
3731 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003732}
3733
3734TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3735 EXPECT_TRUE(matches(
3736 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003737 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003738 isTemplateInstantiation())));
3739}
3740
3741TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3742 EXPECT_TRUE(matches(
3743 "template <typename T> class X { T t; }; class A {};"
3744 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003745 recordDecl(isTemplateInstantiation(), hasDescendant(
3746 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003747}
3748
3749TEST(IsTemplateInstantiation,
3750 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3751 EXPECT_TRUE(matches(
3752 "template <typename T> class X {};"
3753 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003754 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003755}
3756
3757TEST(IsTemplateInstantiation,
3758 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3759 EXPECT_TRUE(matches(
3760 "class A {};"
3761 "class X {"
3762 " template <typename U> class Y { U u; };"
3763 " Y<A> y;"
3764 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003765 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003766}
3767
3768TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3769 // FIXME: Figure out whether this makes sense. It doesn't affect the
3770 // normal use case as long as the uppermost instantiation always is marked
3771 // as template instantiation, but it might be confusing as a predicate.
3772 EXPECT_TRUE(matches(
3773 "class A {};"
3774 "template <typename T> class X {"
3775 " template <typename U> class Y { U u; };"
3776 " Y<T> y;"
3777 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003778 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003779}
3780
3781TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3782 EXPECT_TRUE(notMatches(
3783 "template <typename T> class X {}; class A {};"
3784 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003785 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003786}
3787
3788TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3789 EXPECT_TRUE(notMatches(
3790 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003791 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003792}
3793
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003794TEST(IsInstantiated, MatchesInstantiation) {
3795 EXPECT_TRUE(
3796 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3797 recordDecl(isInstantiated())));
3798}
3799
3800TEST(IsInstantiated, NotMatchesDefinition) {
3801 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3802 recordDecl(isInstantiated())));
3803}
3804
3805TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3806 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3807 "class Y { A<int> a; }; Y y;",
3808 declStmt(isInTemplateInstantiation())));
3809}
3810
3811TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3812 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3813 declStmt(isInTemplateInstantiation())));
3814}
3815
3816TEST(IsInstantiated, MatchesFunctionInstantiation) {
3817 EXPECT_TRUE(
3818 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3819 functionDecl(isInstantiated())));
3820}
3821
3822TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3823 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3824 varDecl(isInstantiated())));
3825}
3826
3827TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3828 EXPECT_TRUE(
3829 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3830 declStmt(isInTemplateInstantiation())));
3831}
3832
3833TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3834 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3835 declStmt(isInTemplateInstantiation())));
3836}
3837
3838TEST(IsInTemplateInstantiation, Sharing) {
3839 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3840 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3841 // and makes the matcher behave in non-obvious ways.
3842 EXPECT_TRUE(notMatches(
3843 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3844 Matcher));
3845 EXPECT_TRUE(matches(
3846 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3847 Matcher));
3848}
3849
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003850TEST(IsExplicitTemplateSpecialization,
3851 DoesNotMatchPrimaryTemplate) {
3852 EXPECT_TRUE(notMatches(
3853 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003854 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003855 EXPECT_TRUE(notMatches(
3856 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003857 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003858}
3859
3860TEST(IsExplicitTemplateSpecialization,
3861 DoesNotMatchExplicitTemplateInstantiations) {
3862 EXPECT_TRUE(notMatches(
3863 "template <typename T> class X {};"
3864 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003865 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003866 EXPECT_TRUE(notMatches(
3867 "template <typename T> void f(T t) {}"
3868 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003869 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003870}
3871
3872TEST(IsExplicitTemplateSpecialization,
3873 DoesNotMatchImplicitTemplateInstantiations) {
3874 EXPECT_TRUE(notMatches(
3875 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003876 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003877 EXPECT_TRUE(notMatches(
3878 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003879 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003880}
3881
3882TEST(IsExplicitTemplateSpecialization,
3883 MatchesExplicitTemplateSpecializations) {
3884 EXPECT_TRUE(matches(
3885 "template <typename T> class X {};"
3886 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003887 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003888 EXPECT_TRUE(matches(
3889 "template <typename T> void f(T t) {}"
3890 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003891 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003892}
3893
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003894TEST(HasAncenstor, MatchesDeclarationAncestors) {
3895 EXPECT_TRUE(matches(
3896 "class A { class B { class C {}; }; };",
3897 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3898}
3899
3900TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3901 EXPECT_TRUE(notMatches(
3902 "class A { class B { class C {}; }; };",
3903 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3904}
3905
3906TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3907 EXPECT_TRUE(matches(
3908 "class A { class B { void f() { C c; } class C {}; }; };",
3909 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3910 hasAncestor(recordDecl(hasName("A"))))))));
3911}
3912
3913TEST(HasAncenstor, MatchesStatementAncestors) {
3914 EXPECT_TRUE(matches(
3915 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003916 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003917}
3918
3919TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3920 EXPECT_TRUE(matches(
3921 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003922 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003923}
3924
3925TEST(HasAncestor, BindsRecursiveCombinations) {
3926 EXPECT_TRUE(matchAndVerifyResultTrue(
3927 "class C { class D { class E { class F { int y; }; }; }; };",
3928 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003929 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003930}
3931
3932TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3933 EXPECT_TRUE(matchAndVerifyResultTrue(
3934 "class C { class D { class E { class F { int y; }; }; }; };",
3935 fieldDecl(hasAncestor(
3936 decl(
3937 hasDescendant(recordDecl(isDefinition(),
3938 hasAncestor(recordDecl())))
3939 ).bind("d")
3940 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003941 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003942}
3943
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003944TEST(HasAncestor, MatchesClosestAncestor) {
3945 EXPECT_TRUE(matchAndVerifyResultTrue(
3946 "template <typename T> struct C {"
3947 " void f(int) {"
3948 " struct I { void g(T) { int x; } } i; i.g(42);"
3949 " }"
3950 "};"
3951 "template struct C<int>;",
3952 varDecl(hasName("x"),
3953 hasAncestor(functionDecl(hasParameter(
3954 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3955 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3956}
3957
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003958TEST(HasAncestor, MatchesInTemplateInstantiations) {
3959 EXPECT_TRUE(matches(
3960 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3961 "A<int>::B::C a;",
3962 fieldDecl(hasType(asString("int")),
3963 hasAncestor(recordDecl(hasName("A"))))));
3964}
3965
3966TEST(HasAncestor, MatchesInImplicitCode) {
3967 EXPECT_TRUE(matches(
3968 "struct X {}; struct A { A() {} X x; };",
3969 constructorDecl(
3970 hasAnyConstructorInitializer(withInitializer(expr(
3971 hasAncestor(recordDecl(hasName("A")))))))));
3972}
3973
Daniel Jasper632aea92012-10-22 16:26:51 +00003974TEST(HasParent, MatchesOnlyParent) {
3975 EXPECT_TRUE(matches(
3976 "void f() { if (true) { int x = 42; } }",
3977 compoundStmt(hasParent(ifStmt()))));
3978 EXPECT_TRUE(notMatches(
3979 "void f() { for (;;) { int x = 42; } }",
3980 compoundStmt(hasParent(ifStmt()))));
3981 EXPECT_TRUE(notMatches(
3982 "void f() { if (true) for (;;) { int x = 42; } }",
3983 compoundStmt(hasParent(ifStmt()))));
3984}
3985
Manuel Klimekc844a462012-12-06 14:42:48 +00003986TEST(HasAncestor, MatchesAllAncestors) {
3987 EXPECT_TRUE(matches(
3988 "template <typename T> struct C { static void f() { 42; } };"
3989 "void t() { C<int>::f(); }",
3990 integerLiteral(
3991 equals(42),
3992 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3993 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3994}
3995
3996TEST(HasParent, MatchesAllParents) {
3997 EXPECT_TRUE(matches(
3998 "template <typename T> struct C { static void f() { 42; } };"
3999 "void t() { C<int>::f(); }",
4000 integerLiteral(
4001 equals(42),
4002 hasParent(compoundStmt(hasParent(functionDecl(
4003 hasParent(recordDecl(isTemplateInstantiation())))))))));
4004 EXPECT_TRUE(matches(
4005 "template <typename T> struct C { static void f() { 42; } };"
4006 "void t() { C<int>::f(); }",
4007 integerLiteral(
4008 equals(42),
4009 hasParent(compoundStmt(hasParent(functionDecl(
4010 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
4011 EXPECT_TRUE(matches(
4012 "template <typename T> struct C { static void f() { 42; } };"
4013 "void t() { C<int>::f(); }",
4014 integerLiteral(equals(42),
4015 hasParent(compoundStmt(allOf(
4016 hasParent(functionDecl(
4017 hasParent(recordDecl(isTemplateInstantiation())))),
4018 hasParent(functionDecl(hasParent(recordDecl(
4019 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00004020 EXPECT_TRUE(
4021 notMatches("template <typename T> struct C { static void f() {} };"
4022 "void t() { C<int>::f(); }",
4023 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004024}
4025
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00004026TEST(HasParent, NoDuplicateParents) {
4027 class HasDuplicateParents : public BoundNodesCallback {
4028 public:
4029 bool run(const BoundNodes *Nodes) override { return false; }
4030 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
4031 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
4032 std::set<const void *> Parents;
4033 for (const auto &Parent : Context->getParents(*Node)) {
4034 if (!Parents.insert(Parent.getMemoizationData()).second) {
4035 return true;
4036 }
4037 }
4038 return false;
4039 }
4040 };
4041 EXPECT_FALSE(matchAndVerifyResultTrue(
4042 "template <typename T> int Foo() { return 1 + 2; }\n"
4043 "int x = Foo<int>() + Foo<unsigned>();",
4044 stmt().bind("node"), new HasDuplicateParents()));
4045}
4046
Daniel Jasper516b02e2012-10-17 08:52:59 +00004047TEST(TypeMatching, MatchesTypes) {
4048 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
4049}
4050
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004051TEST(TypeMatching, MatchesVoid) {
4052 EXPECT_TRUE(
4053 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
4054}
4055
Daniel Jasper516b02e2012-10-17 08:52:59 +00004056TEST(TypeMatching, MatchesArrayTypes) {
4057 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
4058 EXPECT_TRUE(matches("int a[42];", arrayType()));
4059 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
4060
4061 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
4062 arrayType(hasElementType(builtinType()))));
4063
4064 EXPECT_TRUE(matches(
4065 "int const a[] = { 2, 3 };",
4066 qualType(arrayType(hasElementType(builtinType())))));
4067 EXPECT_TRUE(matches(
4068 "int const a[] = { 2, 3 };",
4069 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4070 EXPECT_TRUE(matches(
4071 "typedef const int T; T x[] = { 1, 2 };",
4072 qualType(isConstQualified(), arrayType())));
4073
4074 EXPECT_TRUE(notMatches(
4075 "int a[] = { 2, 3 };",
4076 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4077 EXPECT_TRUE(notMatches(
4078 "int a[] = { 2, 3 };",
4079 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
4080 EXPECT_TRUE(notMatches(
4081 "int const a[] = { 2, 3 };",
4082 qualType(arrayType(hasElementType(builtinType())),
4083 unless(isConstQualified()))));
4084
4085 EXPECT_TRUE(matches("int a[2];",
4086 constantArrayType(hasElementType(builtinType()))));
4087 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
4088}
4089
4090TEST(TypeMatching, MatchesComplexTypes) {
4091 EXPECT_TRUE(matches("_Complex float f;", complexType()));
4092 EXPECT_TRUE(matches(
4093 "_Complex float f;",
4094 complexType(hasElementType(builtinType()))));
4095 EXPECT_TRUE(notMatches(
4096 "_Complex float f;",
4097 complexType(hasElementType(isInteger()))));
4098}
4099
4100TEST(TypeMatching, MatchesConstantArrayTypes) {
4101 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
4102 EXPECT_TRUE(notMatches(
4103 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
4104 constantArrayType(hasElementType(builtinType()))));
4105
4106 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
4107 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
4108 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
4109}
4110
4111TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
4112 EXPECT_TRUE(matches(
4113 "template <typename T, int Size> class array { T data[Size]; };",
4114 dependentSizedArrayType()));
4115 EXPECT_TRUE(notMatches(
4116 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
4117 dependentSizedArrayType()));
4118}
4119
4120TEST(TypeMatching, MatchesIncompleteArrayType) {
4121 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
4122 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
4123
4124 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
4125 incompleteArrayType()));
4126}
4127
4128TEST(TypeMatching, MatchesVariableArrayType) {
4129 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
4130 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4131
4132 EXPECT_TRUE(matches(
4133 "void f(int b) { int a[b]; }",
4134 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4135 varDecl(hasName("b")))))))));
4136}
4137
4138TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00004139 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4140 llvm::Triple::Win32) {
4141 // FIXME: Make this work for MSVC.
4142 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004143
David Majnemer197e2102014-03-05 06:32:38 +00004144 EXPECT_TRUE(matches("_Atomic(int) i;",
4145 atomicType(hasValueType(isInteger()))));
4146 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4147 atomicType(hasValueType(isInteger()))));
4148 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004149}
4150
4151TEST(TypeMatching, MatchesAutoTypes) {
4152 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4153 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4154 autoType()));
4155
Richard Smith061f1e22013-04-30 21:23:01 +00004156 // FIXME: Matching against the type-as-written can't work here, because the
4157 // type as written was not deduced.
4158 //EXPECT_TRUE(matches("auto a = 1;",
4159 // autoType(hasDeducedType(isInteger()))));
4160 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4161 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004162}
4163
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004164TEST(TypeMatching, MatchesFunctionTypes) {
4165 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4166 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4167}
4168
Edwin Vaneec074802013-04-01 18:33:34 +00004169TEST(TypeMatching, MatchesParenType) {
4170 EXPECT_TRUE(
4171 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4172 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4173
4174 EXPECT_TRUE(matches(
4175 "int (*ptr_to_func)(int);",
4176 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4177 EXPECT_TRUE(notMatches(
4178 "int (*ptr_to_array)[4];",
4179 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4180}
4181
Daniel Jasper516b02e2012-10-17 08:52:59 +00004182TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004183 // FIXME: Reactive when these tests can be more specific (not matching
4184 // implicit code on certain platforms), likely when we have hasDescendant for
4185 // Types/TypeLocs.
4186 //EXPECT_TRUE(matchAndVerifyResultTrue(
4187 // "int* a;",
4188 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4189 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4190 //EXPECT_TRUE(matchAndVerifyResultTrue(
4191 // "int* a;",
4192 // pointerTypeLoc().bind("loc"),
4193 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004194 EXPECT_TRUE(matches(
4195 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004196 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004197 EXPECT_TRUE(matches(
4198 "int** a;",
4199 loc(pointerType(pointee(pointerType())))));
4200 EXPECT_TRUE(matches(
4201 "int* b; int* * const a = &b;",
4202 loc(qualType(isConstQualified(), pointerType()))));
4203
4204 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004205 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4206 hasType(blockPointerType()))));
4207 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4208 hasType(memberPointerType()))));
4209 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4210 hasType(pointerType()))));
4211 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4212 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004213 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4214 hasType(lValueReferenceType()))));
4215 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4216 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004217
Daniel Jasper7943eb52012-10-17 13:35:36 +00004218 Fragment = "int *ptr;";
4219 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4220 hasType(blockPointerType()))));
4221 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4222 hasType(memberPointerType()))));
4223 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4224 hasType(pointerType()))));
4225 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4226 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004227
Daniel Jasper7943eb52012-10-17 13:35:36 +00004228 Fragment = "int a; int &ref = a;";
4229 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4230 hasType(blockPointerType()))));
4231 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4232 hasType(memberPointerType()))));
4233 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4234 hasType(pointerType()))));
4235 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4236 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004237 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4238 hasType(lValueReferenceType()))));
4239 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4240 hasType(rValueReferenceType()))));
4241
4242 Fragment = "int &&ref = 2;";
4243 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4244 hasType(blockPointerType()))));
4245 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4246 hasType(memberPointerType()))));
4247 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4248 hasType(pointerType()))));
4249 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4250 hasType(referenceType()))));
4251 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4252 hasType(lValueReferenceType()))));
4253 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4254 hasType(rValueReferenceType()))));
4255}
4256
4257TEST(TypeMatching, AutoRefTypes) {
4258 std::string Fragment = "auto a = 1;"
4259 "auto b = a;"
4260 "auto &c = a;"
4261 "auto &&d = c;"
4262 "auto &&e = 2;";
4263 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4264 hasType(referenceType()))));
4265 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4266 hasType(referenceType()))));
4267 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4268 hasType(referenceType()))));
4269 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4270 hasType(lValueReferenceType()))));
4271 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4272 hasType(rValueReferenceType()))));
4273 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4274 hasType(referenceType()))));
4275 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4276 hasType(lValueReferenceType()))));
4277 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4278 hasType(rValueReferenceType()))));
4279 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4280 hasType(referenceType()))));
4281 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4282 hasType(lValueReferenceType()))));
4283 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4284 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004285}
4286
4287TEST(TypeMatching, PointeeTypes) {
4288 EXPECT_TRUE(matches("int b; int &a = b;",
4289 referenceType(pointee(builtinType()))));
4290 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4291
4292 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004293 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004294
4295 EXPECT_TRUE(matches(
4296 "int const *A;",
4297 pointerType(pointee(isConstQualified(), builtinType()))));
4298 EXPECT_TRUE(notMatches(
4299 "int *A;",
4300 pointerType(pointee(isConstQualified(), builtinType()))));
4301}
4302
4303TEST(TypeMatching, MatchesPointersToConstTypes) {
4304 EXPECT_TRUE(matches("int b; int * const a = &b;",
4305 loc(pointerType())));
4306 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004307 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004308 EXPECT_TRUE(matches(
4309 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004310 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004311 EXPECT_TRUE(matches(
4312 "int b; const int * a = &b;",
4313 pointerType(pointee(builtinType()))));
4314}
4315
4316TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004317 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4318 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004319}
4320
Edwin Vanef901b712013-02-25 14:49:29 +00004321TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004322 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004323 templateSpecializationType()));
4324}
4325
Edwin Vaneb6eae142013-02-25 20:43:32 +00004326TEST(TypeMatching, MatchesRecordType) {
4327 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004328 EXPECT_TRUE(matches("struct S{}; S s;",
4329 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4330 EXPECT_TRUE(notMatches("int i;",
4331 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004332}
4333
4334TEST(TypeMatching, MatchesElaboratedType) {
4335 EXPECT_TRUE(matches(
4336 "namespace N {"
4337 " namespace M {"
4338 " class D {};"
4339 " }"
4340 "}"
4341 "N::M::D d;", elaboratedType()));
4342 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4343 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4344}
4345
4346TEST(ElaboratedTypeNarrowing, hasQualifier) {
4347 EXPECT_TRUE(matches(
4348 "namespace N {"
4349 " namespace M {"
4350 " class D {};"
4351 " }"
4352 "}"
4353 "N::M::D d;",
4354 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4355 EXPECT_TRUE(notMatches(
4356 "namespace M {"
4357 " class D {};"
4358 "}"
4359 "M::D d;",
4360 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004361 EXPECT_TRUE(notMatches(
4362 "struct D {"
4363 "} d;",
4364 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004365}
4366
4367TEST(ElaboratedTypeNarrowing, namesType) {
4368 EXPECT_TRUE(matches(
4369 "namespace N {"
4370 " namespace M {"
4371 " class D {};"
4372 " }"
4373 "}"
4374 "N::M::D d;",
4375 elaboratedType(elaboratedType(namesType(recordType(
4376 hasDeclaration(namedDecl(hasName("D")))))))));
4377 EXPECT_TRUE(notMatches(
4378 "namespace M {"
4379 " class D {};"
4380 "}"
4381 "M::D d;",
4382 elaboratedType(elaboratedType(namesType(typedefType())))));
4383}
4384
Samuel Benzaquenf8ec4542015-08-26 16:15:59 +00004385TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
4386 const std::string code = "template <typename T>"
4387 "int F() {"
4388 " return 1 + T();"
4389 "}"
4390 "int i = F<int>();";
4391 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
4392 expr(hasType(substTemplateTypeParmType()))))));
4393 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
4394 expr(hasType(substTemplateTypeParmType()))))));
4395}
4396
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004397TEST(NNS, MatchesNestedNameSpecifiers) {
4398 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4399 nestedNameSpecifier()));
4400 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4401 nestedNameSpecifier()));
4402 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4403 nestedNameSpecifier()));
4404
4405 EXPECT_TRUE(matches(
4406 "struct A { static void f() {} }; void g() { A::f(); }",
4407 nestedNameSpecifier()));
4408 EXPECT_TRUE(notMatches(
4409 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4410 nestedNameSpecifier()));
4411}
4412
Daniel Jasper87c3d362012-09-20 14:12:57 +00004413TEST(NullStatement, SimpleCases) {
4414 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4415 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4416}
4417
Aaron Ballman11825f22015-08-18 19:55:20 +00004418TEST(NS, Anonymous) {
4419 EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
4420 EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
4421}
4422
Aaron Ballman6c79f352015-08-28 19:39:21 +00004423TEST(NS, Alias) {
4424 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
4425 namespaceAliasDecl(hasName("alias"))));
4426}
4427
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004428TEST(NNS, MatchesTypes) {
4429 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4430 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4431 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4432 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4433 Matcher));
4434 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4435}
4436
4437TEST(NNS, MatchesNamespaceDecls) {
4438 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4439 specifiesNamespace(hasName("ns")));
4440 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4441 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4442 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4443}
4444
4445TEST(NNS, BindsNestedNameSpecifiers) {
4446 EXPECT_TRUE(matchAndVerifyResultTrue(
4447 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4448 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4449 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4450}
4451
4452TEST(NNS, BindsNestedNameSpecifierLocs) {
4453 EXPECT_TRUE(matchAndVerifyResultTrue(
4454 "namespace ns { struct B {}; } ns::B b;",
4455 loc(nestedNameSpecifier()).bind("loc"),
4456 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4457}
4458
4459TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4460 EXPECT_TRUE(matches(
4461 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4462 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4463 EXPECT_TRUE(matches(
4464 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004465 nestedNameSpecifierLoc(hasPrefix(
4466 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004467}
4468
Daniel Jasper6fc34332012-10-30 15:42:00 +00004469TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4470 std::string Fragment =
4471 "namespace a { struct A { struct B { struct C {}; }; }; };"
4472 "void f() { a::A::B::C c; }";
4473 EXPECT_TRUE(matches(
4474 Fragment,
4475 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4476 hasDescendant(nestedNameSpecifier(
4477 specifiesNamespace(hasName("a")))))));
4478 EXPECT_TRUE(notMatches(
4479 Fragment,
4480 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4481 has(nestedNameSpecifier(
4482 specifiesNamespace(hasName("a")))))));
4483 EXPECT_TRUE(matches(
4484 Fragment,
4485 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4486 has(nestedNameSpecifier(
4487 specifiesNamespace(hasName("a")))))));
4488
4489 // Not really useful because a NestedNameSpecifier can af at most one child,
4490 // but to complete the interface.
4491 EXPECT_TRUE(matchAndVerifyResultTrue(
4492 Fragment,
4493 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4494 forEach(nestedNameSpecifier().bind("x"))),
4495 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4496}
4497
4498TEST(NNS, NestedNameSpecifiersAsDescendants) {
4499 std::string Fragment =
4500 "namespace a { struct A { struct B { struct C {}; }; }; };"
4501 "void f() { a::A::B::C c; }";
4502 EXPECT_TRUE(matches(
4503 Fragment,
4504 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4505 asString("struct a::A")))))));
4506 EXPECT_TRUE(matchAndVerifyResultTrue(
4507 Fragment,
4508 functionDecl(hasName("f"),
4509 forEachDescendant(nestedNameSpecifier().bind("x"))),
4510 // Nested names: a, a::A and a::A::B.
4511 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4512}
4513
4514TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4515 std::string Fragment =
4516 "namespace a { struct A { struct B { struct C {}; }; }; };"
4517 "void f() { a::A::B::C c; }";
4518 EXPECT_TRUE(matches(
4519 Fragment,
4520 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4521 hasDescendant(loc(nestedNameSpecifier(
4522 specifiesNamespace(hasName("a"))))))));
4523 EXPECT_TRUE(notMatches(
4524 Fragment,
4525 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4526 has(loc(nestedNameSpecifier(
4527 specifiesNamespace(hasName("a"))))))));
4528 EXPECT_TRUE(matches(
4529 Fragment,
4530 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4531 has(loc(nestedNameSpecifier(
4532 specifiesNamespace(hasName("a"))))))));
4533
4534 EXPECT_TRUE(matchAndVerifyResultTrue(
4535 Fragment,
4536 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4537 forEach(nestedNameSpecifierLoc().bind("x"))),
4538 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4539}
4540
4541TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4542 std::string Fragment =
4543 "namespace a { struct A { struct B { struct C {}; }; }; };"
4544 "void f() { a::A::B::C c; }";
4545 EXPECT_TRUE(matches(
4546 Fragment,
4547 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4548 asString("struct a::A"))))))));
4549 EXPECT_TRUE(matchAndVerifyResultTrue(
4550 Fragment,
4551 functionDecl(hasName("f"),
4552 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4553 // Nested names: a, a::A and a::A::B.
4554 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4555}
4556
Manuel Klimek191c0932013-02-01 13:41:35 +00004557template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004558public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004559 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4560 StringRef InnerId)
4561 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004562 }
4563
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004564 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004565
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004566 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004567 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004568 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4569 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004570 }
4571private:
4572 std::string Id;
4573 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004574 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004575};
4576
4577TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004578 EXPECT_TRUE(matchAndVerifyResultTrue(
4579 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4580 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004581 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4582 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004583 EXPECT_TRUE(matchAndVerifyResultFalse(
4584 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4585 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004586 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4587 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004588}
4589
4590TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004591 EXPECT_TRUE(matchAndVerifyResultTrue(
4592 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004593 new VerifyMatchOnNode<clang::Stmt>(
4594 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004595 EXPECT_TRUE(matchAndVerifyResultFalse(
4596 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004597 new VerifyMatchOnNode<clang::Stmt>(
4598 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004599}
4600
4601TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4602 EXPECT_TRUE(matchAndVerifyResultTrue(
4603 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4604 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004605 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004606 EXPECT_TRUE(matchAndVerifyResultFalse(
4607 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4608 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004609 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004610}
4611
Manuel Klimekbee08572013-02-07 12:42:10 +00004612template <typename T>
4613class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4614public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004615 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004616
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004617 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004618 const T *Node = Nodes->getNodeAs<T>("");
4619 return verify(*Nodes, *Context, Node);
4620 }
4621
4622 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004623 // Use the original typed pointer to verify we can pass pointers to subtypes
4624 // to equalsNode.
4625 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004626 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004627 "", match(stmt(hasParent(
4628 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004629 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004630 }
4631 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004632 // Use the original typed pointer to verify we can pass pointers to subtypes
4633 // to equalsNode.
4634 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004635 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004636 "", match(decl(hasParent(
4637 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004638 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004639 }
4640};
4641
4642TEST(IsEqualTo, MatchesNodesByIdentity) {
4643 EXPECT_TRUE(matchAndVerifyResultTrue(
4644 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004645 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4646 EXPECT_TRUE(matchAndVerifyResultTrue(
4647 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4648 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004649}
4650
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004651TEST(MatchFinder, CheckProfiling) {
4652 MatchFinder::MatchFinderOptions Options;
4653 llvm::StringMap<llvm::TimeRecord> Records;
4654 Options.CheckProfiling.emplace(Records);
4655 MatchFinder Finder(std::move(Options));
4656
4657 struct NamedCallback : public MatchFinder::MatchCallback {
4658 void run(const MatchFinder::MatchResult &Result) override {}
4659 StringRef getID() const override { return "MyID"; }
4660 } Callback;
4661 Finder.addMatcher(decl(), &Callback);
4662 std::unique_ptr<FrontendActionFactory> Factory(
4663 newFrontendActionFactory(&Finder));
4664 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4665
4666 EXPECT_EQ(1u, Records.size());
4667 EXPECT_EQ("MyID", Records.begin()->getKey());
4668}
4669
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004670class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4671public:
4672 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004673 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004674 EXPECT_TRUE(Called);
4675 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004676 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004677 bool Called;
4678};
4679
4680TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4681 MatchFinder Finder;
4682 VerifyStartOfTranslationUnit VerifyCallback;
4683 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004684 std::unique_ptr<FrontendActionFactory> Factory(
4685 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004686 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4687 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004688
4689 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004690 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004691 ASSERT_TRUE(AST.get());
4692 Finder.matchAST(AST->getASTContext());
4693 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004694}
4695
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004696class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4697public:
4698 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004699 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004700 EXPECT_FALSE(Called);
4701 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004702 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004703 bool Called;
4704};
4705
4706TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4707 MatchFinder Finder;
4708 VerifyEndOfTranslationUnit VerifyCallback;
4709 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004710 std::unique_ptr<FrontendActionFactory> Factory(
4711 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004712 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4713 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004714
4715 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004716 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004717 ASSERT_TRUE(AST.get());
4718 Finder.matchAST(AST->getASTContext());
4719 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004720}
4721
Manuel Klimekbbb75852013-06-20 14:06:32 +00004722TEST(EqualsBoundNodeMatcher, QualType) {
4723 EXPECT_TRUE(matches(
4724 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4725 hasInitializer(ignoringParenImpCasts(
4726 hasType(qualType(equalsBoundNode("type"))))))));
4727 EXPECT_TRUE(notMatches("int i = 1.f;",
4728 varDecl(hasType(qualType().bind("type")),
4729 hasInitializer(ignoringParenImpCasts(hasType(
4730 qualType(equalsBoundNode("type"))))))));
4731}
4732
4733TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4734 EXPECT_TRUE(notMatches(
4735 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4736 hasInitializer(ignoringParenImpCasts(
4737 hasType(qualType(equalsBoundNode("type"))))))));
4738}
4739
4740TEST(EqualsBoundNodeMatcher, Stmt) {
4741 EXPECT_TRUE(
4742 matches("void f() { if(true) {} }",
4743 stmt(allOf(ifStmt().bind("if"),
4744 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4745
4746 EXPECT_TRUE(notMatches(
4747 "void f() { if(true) { if (true) {} } }",
4748 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4749}
4750
4751TEST(EqualsBoundNodeMatcher, Decl) {
4752 EXPECT_TRUE(matches(
4753 "class X { class Y {}; };",
4754 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4755 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4756
4757 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4758 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4759 has(decl(equalsBoundNode("record")))))));
4760}
4761
4762TEST(EqualsBoundNodeMatcher, Type) {
4763 EXPECT_TRUE(matches(
4764 "class X { int a; int b; };",
4765 recordDecl(
4766 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4767 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4768
4769 EXPECT_TRUE(notMatches(
4770 "class X { int a; double b; };",
4771 recordDecl(
4772 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4773 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4774}
4775
4776TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004777 EXPECT_TRUE(matchAndVerifyResultTrue(
4778 "int f() {"
4779 " if (1) {"
4780 " int i = 9;"
4781 " }"
4782 " int j = 10;"
4783 " {"
4784 " float k = 9.0;"
4785 " }"
4786 " return 0;"
4787 "}",
4788 // Look for variable declarations within functions whose type is the same
4789 // as the function return type.
4790 functionDecl(returns(qualType().bind("type")),
4791 forEachDescendant(varDecl(hasType(
4792 qualType(equalsBoundNode("type")))).bind("decl"))),
4793 // Only i and j should match, not k.
4794 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4795}
4796
4797TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4798 EXPECT_TRUE(matchAndVerifyResultTrue(
4799 "void f() {"
4800 " int x;"
4801 " double d;"
4802 " x = d + x - d + x;"
4803 "}",
4804 functionDecl(
4805 hasName("f"), forEachDescendant(varDecl().bind("d")),
4806 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4807 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4808}
4809
Manuel Klimekce68f772014-03-25 14:39:26 +00004810TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4811 EXPECT_TRUE(matchAndVerifyResultTrue(
4812 "struct StringRef { int size() const; const char* data() const; };"
4813 "void f(StringRef v) {"
4814 " v.data();"
4815 "}",
4816 memberCallExpr(
4817 callee(methodDecl(hasName("data"))),
4818 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4819 .bind("var")))),
4820 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4821 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4822 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4823 .bind("data"),
4824 new VerifyIdIsBoundTo<Expr>("data", 1)));
4825
4826 EXPECT_FALSE(matches(
4827 "struct StringRef { int size() const; const char* data() const; };"
4828 "void f(StringRef v) {"
4829 " v.data();"
4830 " v.size();"
4831 "}",
4832 memberCallExpr(
4833 callee(methodDecl(hasName("data"))),
4834 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4835 .bind("var")))),
4836 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4837 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4838 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4839 .bind("data")));
4840}
4841
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004842TEST(TypeDefDeclMatcher, Match) {
4843 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4844 typedefDecl(hasName("typedefDeclTest"))));
4845}
4846
Aaron Ballman11825f22015-08-18 19:55:20 +00004847TEST(IsInlineMatcher, IsInline) {
4848 EXPECT_TRUE(matches("void g(); inline void f();",
4849 functionDecl(isInline(), hasName("f"))));
4850 EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
4851 namespaceDecl(isInline(), hasName("m"))));
4852}
4853
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004854// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4855#ifndef LLVM_ON_WIN32
4856
4857TEST(Matcher, IsExpansionInMainFileMatcher) {
4858 EXPECT_TRUE(matches("class X {};",
4859 recordDecl(hasName("X"), isExpansionInMainFile())));
4860 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4861 FileContentMappings M;
4862 M.push_back(std::make_pair("/other", "class X {};"));
4863 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4864 recordDecl(isExpansionInMainFile()), false,
4865 "-isystem/", M));
4866}
4867
4868TEST(Matcher, IsExpansionInSystemHeader) {
4869 FileContentMappings M;
4870 M.push_back(std::make_pair("/other", "class X {};"));
4871 EXPECT_TRUE(matchesConditionally(
4872 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4873 "-isystem/", M));
4874 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4875 recordDecl(isExpansionInSystemHeader()),
4876 false, "-I/", M));
4877 EXPECT_TRUE(notMatches("class X {};",
4878 recordDecl(isExpansionInSystemHeader())));
4879 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4880}
4881
4882TEST(Matcher, IsExpansionInFileMatching) {
4883 FileContentMappings M;
4884 M.push_back(std::make_pair("/foo", "class A {};"));
4885 M.push_back(std::make_pair("/bar", "class B {};"));
4886 EXPECT_TRUE(matchesConditionally(
4887 "#include <foo>\n"
4888 "#include <bar>\n"
4889 "class X {};",
4890 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4891 "-isystem/", M));
4892 EXPECT_TRUE(matchesConditionally(
4893 "#include <foo>\n"
4894 "#include <bar>\n"
4895 "class X {};",
4896 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4897 "-isystem/", M));
4898}
4899
4900#endif // LLVM_ON_WIN32
4901
Manuel Klimekbfa43572015-03-12 15:48:15 +00004902
4903TEST(ObjCMessageExprMatcher, SimpleExprs) {
4904 // don't find ObjCMessageExpr where none are present
4905 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
4906
4907 std::string Objc1String =
4908 "@interface Str "
4909 " - (Str *)uppercaseString:(Str *)str;"
4910 "@end "
4911 "@interface foo "
4912 "- (void)meth:(Str *)text;"
4913 "@end "
4914 " "
4915 "@implementation foo "
4916 "- (void) meth:(Str *)text { "
4917 " [self contents];"
4918 " Str *up = [text uppercaseString];"
4919 "} "
4920 "@end ";
4921 EXPECT_TRUE(matchesObjC(
4922 Objc1String,
4923 objcMessageExpr(anything())));
4924 EXPECT_TRUE(matchesObjC(
4925 Objc1String,
4926 objcMessageExpr(hasSelector("contents"))));
4927 EXPECT_TRUE(matchesObjC(
4928 Objc1String,
4929 objcMessageExpr(matchesSelector("cont*"))));
4930 EXPECT_FALSE(matchesObjC(
4931 Objc1String,
4932 objcMessageExpr(matchesSelector("?cont*"))));
4933 EXPECT_TRUE(notMatchesObjC(
4934 Objc1String,
4935 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
4936 EXPECT_TRUE(matchesObjC(
4937 Objc1String,
4938 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
4939 EXPECT_TRUE(matchesObjC(
4940 Objc1String,
Manuel Klimeke67a9d62015-09-08 10:11:26 +00004941 objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
4942 EXPECT_TRUE(matchesObjC(
4943 Objc1String,
Manuel Klimekbfa43572015-03-12 15:48:15 +00004944 objcMessageExpr(matchesSelector("uppercase*"),
4945 argumentCountIs(0)
4946 )));
4947
4948}
4949
Manuel Klimek04616e42012-07-06 05:48:52 +00004950} // end namespace ast_matchers
4951} // end namespace clang