blob: ae363e974b5d4c1284cbf64927a44c34e0b6510f [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
Manuel Klimek04616e42012-07-06 05:48:52 +0000456TEST(DeclarationMatcher, MatchAnyOf) {
457 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000458 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000459 EXPECT_TRUE(
460 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
461 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
462 EXPECT_TRUE(
463 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
464 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
465
Daniel Jasper84c763e2012-07-15 19:57:12 +0000466 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000467 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000468 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
469 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
470
Manuel Klimek04616e42012-07-06 05:48:52 +0000471 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000472 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
473 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000474 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
475 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
476 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
477 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
478 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
479 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000480
481 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
482 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
483 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
484 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Manuel Klimek04616e42012-07-06 05:48:52 +0000485}
486
487TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000488 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000489 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
490 EXPECT_TRUE(matches("class X {};", HasClassX));
491
492 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000493 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000494 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
495 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
496 EXPECT_TRUE(
497 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
498}
499
500TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
501 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000502 recordDecl(
503 has(recordDecl(
504 has(recordDecl(hasName("X"))),
505 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000506 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000507 has(recordDecl(
508 has(recordDecl(hasName("A"))),
509 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000510 hasName("C"))),
511 hasName("F"));
512
513 EXPECT_TRUE(matches(
514 "class F {"
515 " class Z {"
516 " class X {};"
517 " class Y {};"
518 " };"
519 " class C {"
520 " class A {};"
521 " class B {};"
522 " };"
523 "};", Recursive));
524
525 EXPECT_TRUE(matches(
526 "class F {"
527 " class Z {"
528 " class A {};"
529 " class X {};"
530 " class Y {};"
531 " };"
532 " class C {"
533 " class X {};"
534 " class A {};"
535 " class B {};"
536 " };"
537 "};", Recursive));
538
539 EXPECT_TRUE(matches(
540 "class O1 {"
541 " class O2 {"
542 " class F {"
543 " class Z {"
544 " class A {};"
545 " class X {};"
546 " class Y {};"
547 " };"
548 " class C {"
549 " class X {};"
550 " class A {};"
551 " class B {};"
552 " };"
553 " };"
554 " };"
555 "};", Recursive));
556}
557
558TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
559 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000560 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000561 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000562 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000563 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000564 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000565 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000566 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000567 hasName("Y"))),
568 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000569 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000570 anyOf(
571 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000572 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000573 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000574 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000575 hasName("B")))))),
576 hasName("F")));
577
578 EXPECT_TRUE(matches("class F {};", Recursive));
579 EXPECT_TRUE(matches("class Z {};", Recursive));
580 EXPECT_TRUE(matches("class C {};", Recursive));
581 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
582 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
583 EXPECT_TRUE(
584 matches("class O1 { class O2 {"
585 " class M { class N { class B {}; }; }; "
586 "}; };", Recursive));
587}
588
589TEST(DeclarationMatcher, MatchNot) {
590 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000591 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000592 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000593 unless(hasName("X")));
594 EXPECT_TRUE(notMatches("", NotClassX));
595 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
596 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
597 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
598 EXPECT_TRUE(
599 notMatches("class Y {}; class Z {}; class X : public Y {};",
600 NotClassX));
601
602 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000603 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000604 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000605 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000606 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000607 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000608 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
609 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
610 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000611
612 DeclarationMatcher NamedNotRecord =
613 namedDecl(hasName("Foo"), unless(recordDecl()));
614 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
615 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000616}
617
618TEST(DeclarationMatcher, HasDescendant) {
619 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000620 recordDecl(
621 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000622 hasName("Z"));
623 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
624 EXPECT_TRUE(
625 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
626 EXPECT_TRUE(
627 matches("class Z { class A { class Y { class X {}; }; }; };",
628 ZDescendantClassX));
629 EXPECT_TRUE(
630 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
631 ZDescendantClassX));
632 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
633
634 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000635 recordDecl(
636 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000637 hasName("X"))),
638 hasName("Z"));
639 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
640 ZDescendantClassXHasClassY));
641 EXPECT_TRUE(
642 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
643 ZDescendantClassXHasClassY));
644 EXPECT_TRUE(notMatches(
645 "class Z {"
646 " class A {"
647 " class B {"
648 " class X {"
649 " class C {"
650 " class Y {};"
651 " };"
652 " };"
653 " }; "
654 " };"
655 "};", ZDescendantClassXHasClassY));
656
657 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000658 recordDecl(
659 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
660 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000661 hasName("Z"));
662 EXPECT_TRUE(
663 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
664 ZDescendantClassXDescendantClassY));
665 EXPECT_TRUE(matches(
666 "class Z {"
667 " class A {"
668 " class X {"
669 " class B {"
670 " class Y {};"
671 " };"
672 " class Y {};"
673 " };"
674 " };"
675 "};", ZDescendantClassXDescendantClassY));
676}
677
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000678TEST(DeclarationMatcher, HasDescendantMemoization) {
679 DeclarationMatcher CannotMemoize =
680 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
681 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
682}
683
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000684TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
685 auto Name = hasName("i");
686 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
687 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
688 // Matching VD first should not make a cache hit for RD.
689 EXPECT_TRUE(notMatches("void f() { int i; }",
690 decl(hasDescendant(VD), hasDescendant(RD))));
691 EXPECT_TRUE(notMatches("void f() { int i; }",
692 decl(hasDescendant(RD), hasDescendant(VD))));
693 // Not matching RD first should not make a cache hit for VD either.
694 EXPECT_TRUE(matches("void f() { int i; }",
695 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
696}
697
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000698TEST(DeclarationMatcher, HasAttr) {
699 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
700 decl(hasAttr(clang::attr::WarnUnused))));
701 EXPECT_FALSE(matches("struct X {};",
702 decl(hasAttr(clang::attr::WarnUnused))));
703}
704
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000705TEST(DeclarationMatcher, MatchCudaDecl) {
706 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
707 "void g() { f<<<1, 2>>>(); }",
708 CUDAKernelCallExpr()));
709 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000710 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000711 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000712 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000713 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000714 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000715}
716
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000717// Implements a run method that returns whether BoundNodes contains a
718// Decl bound to Id that can be dynamically cast to T.
719// Optionally checks that the check succeeded a specific number of times.
720template <typename T>
721class VerifyIdIsBoundTo : public BoundNodesCallback {
722public:
723 // Create an object that checks that a node of type \c T was bound to \c Id.
724 // Does not check for a certain number of matches.
725 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
726 : Id(Id), ExpectedCount(-1), Count(0) {}
727
728 // Create an object that checks that a node of type \c T was bound to \c Id.
729 // Checks that there were exactly \c ExpectedCount matches.
730 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
731 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
732
733 // Create an object that checks that a node of type \c T was bound to \c Id.
734 // Checks that there was exactly one match with the name \c ExpectedName.
735 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000736 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
737 int ExpectedCount = 1)
738 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
739 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000740
Craig Toppera798a9d2014-03-02 09:32:10 +0000741 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000742 if (ExpectedCount != -1)
743 EXPECT_EQ(ExpectedCount, Count);
744 if (!ExpectedName.empty())
745 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000746 Count = 0;
747 Name.clear();
748 }
749
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000750 ~VerifyIdIsBoundTo() override {
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000751 EXPECT_EQ(0, Count);
752 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000753 }
754
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000755 bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000756 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000757 if (Nodes->getNodeAs<T>(Id)) {
758 ++Count;
759 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
760 Name = Named->getNameAsString();
761 } else if (const NestedNameSpecifier *NNS =
762 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
763 llvm::raw_string_ostream OS(Name);
764 NNS->print(OS, PrintingPolicy(LangOptions()));
765 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000766 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
767 EXPECT_NE(M.end(), I);
768 if (I != M.end())
769 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000770 return true;
771 }
Craig Topper416fa342014-06-08 08:38:12 +0000772 EXPECT_TRUE(M.count(Id) == 0 ||
773 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000774 return false;
775 }
776
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000777 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000778 return run(Nodes);
779 }
780
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000781private:
782 const std::string Id;
783 const int ExpectedCount;
784 int Count;
785 const std::string ExpectedName;
786 std::string Name;
787};
788
789TEST(HasDescendant, MatchesDescendantTypes) {
790 EXPECT_TRUE(matches("void f() { int i = 3; }",
791 decl(hasDescendant(loc(builtinType())))));
792 EXPECT_TRUE(matches("void f() { int i = 3; }",
793 stmt(hasDescendant(builtinType()))));
794
795 EXPECT_TRUE(matches("void f() { int i = 3; }",
796 stmt(hasDescendant(loc(builtinType())))));
797 EXPECT_TRUE(matches("void f() { int i = 3; }",
798 stmt(hasDescendant(qualType(builtinType())))));
799
800 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
801 stmt(hasDescendant(isInteger()))));
802
803 EXPECT_TRUE(matchAndVerifyResultTrue(
804 "void f() { int a; float c; int d; int e; }",
805 functionDecl(forEachDescendant(
806 varDecl(hasDescendant(isInteger())).bind("x"))),
807 new VerifyIdIsBoundTo<Decl>("x", 3)));
808}
809
810TEST(HasDescendant, MatchesDescendantsOfTypes) {
811 EXPECT_TRUE(matches("void f() { int*** i; }",
812 qualType(hasDescendant(builtinType()))));
813 EXPECT_TRUE(matches("void f() { int*** i; }",
814 qualType(hasDescendant(
815 pointerType(pointee(builtinType()))))));
816 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000817 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000818
819 EXPECT_TRUE(matchAndVerifyResultTrue(
820 "void f() { int*** i; }",
821 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
822 new VerifyIdIsBoundTo<Type>("x", 2)));
823}
824
825TEST(Has, MatchesChildrenOfTypes) {
826 EXPECT_TRUE(matches("int i;",
827 varDecl(hasName("i"), has(isInteger()))));
828 EXPECT_TRUE(notMatches("int** i;",
829 varDecl(hasName("i"), has(isInteger()))));
830 EXPECT_TRUE(matchAndVerifyResultTrue(
831 "int (*f)(float, int);",
832 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
833 new VerifyIdIsBoundTo<QualType>("x", 2)));
834}
835
836TEST(Has, MatchesChildTypes) {
837 EXPECT_TRUE(matches(
838 "int* i;",
839 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
840 EXPECT_TRUE(notMatches(
841 "int* i;",
842 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
843}
844
Samuel Benzaquenc640ef52014-10-28 13:33:58 +0000845TEST(ValueDecl, Matches) {
846 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
847 valueDecl(hasType(asString("enum EnumType")))));
848 EXPECT_TRUE(matches("void FunctionDecl();",
849 valueDecl(hasType(asString("void (void)")))));
850}
851
Daniel Jasper1dad1832012-07-10 20:20:19 +0000852TEST(Enum, DoesNotMatchClasses) {
853 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
854}
855
856TEST(Enum, MatchesEnums) {
857 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
858}
859
860TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000861 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000862 EXPECT_TRUE(matches("enum X{ A };", Matcher));
863 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
864 EXPECT_TRUE(notMatches("enum X {};", Matcher));
865}
866
Manuel Klimek04616e42012-07-06 05:48:52 +0000867TEST(StatementMatcher, Has) {
868 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000869 expr(hasType(pointsTo(recordDecl(hasName("X")))),
870 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000871
872 EXPECT_TRUE(matches(
873 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
874 EXPECT_TRUE(notMatches(
875 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
876}
877
878TEST(StatementMatcher, HasDescendant) {
879 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000880 expr(hasType(pointsTo(recordDecl(hasName("X")))),
881 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000882
883 EXPECT_TRUE(matches(
884 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
885 HasDescendantVariableI));
886 EXPECT_TRUE(notMatches(
887 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
888 HasDescendantVariableI));
889}
890
891TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000892 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000893
894 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
895 EXPECT_TRUE(notMatches("class A {};", TypeA));
896
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000897 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000898
899 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
900 TypeDerivedFromA));
901 EXPECT_TRUE(notMatches("class A {};", TypeA));
902
903 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000904 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000905
906 EXPECT_TRUE(
907 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
908}
909
Manuel Klimek04616e42012-07-06 05:48:52 +0000910TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000911 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000912
913 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000914 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000915
916 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000917 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000918
919 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000920 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000921
922 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
923 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000924 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000925
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000926 StatementMatcher MethodX =
927 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000928
929 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
930 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000931 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000932}
933
934TEST(Matcher, BindTheSameNameInAlternatives) {
935 StatementMatcher matcher = anyOf(
936 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000937 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000938 hasRHS(integerLiteral(equals(0)))),
939 binaryOperator(hasOperatorName("+"),
940 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000941 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000942
943 EXPECT_TRUE(matchAndVerifyResultTrue(
944 // The first branch of the matcher binds x to 0 but then fails.
945 // The second branch binds x to f() and succeeds.
946 "int f() { return 0 + f(); }",
947 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000948 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000949}
950
Manuel Klimekfdf98762012-08-30 19:41:06 +0000951TEST(Matcher, BindsIDForMemoizedResults) {
952 // Using the same matcher in two match expressions will make memoization
953 // kick in.
954 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
955 EXPECT_TRUE(matchAndVerifyResultTrue(
956 "class A { class B { class X {}; }; };",
957 DeclarationMatcher(anyOf(
958 recordDecl(hasName("A"), hasDescendant(ClassX)),
959 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000960 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000961}
962
Daniel Jasper856194d02012-12-03 15:43:25 +0000963TEST(HasDeclaration, HasDeclarationOfEnumType) {
964 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
965 expr(hasType(pointsTo(
966 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
967}
968
Edwin Vaneed936452013-02-25 14:32:42 +0000969TEST(HasDeclaration, HasGetDeclTraitTest) {
970 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
971 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
972 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
973}
974
Edwin Vane2c197e02013-02-19 17:14:34 +0000975TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
976 EXPECT_TRUE(matches("typedef int X; X a;",
977 varDecl(hasName("a"),
978 hasType(typedefType(hasDeclaration(decl()))))));
979
980 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
981}
982
Edwin Vanef901b712013-02-25 14:49:29 +0000983TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
984 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
985 varDecl(hasType(templateSpecializationType(
986 hasDeclaration(namedDecl(hasName("A"))))))));
987}
988
Manuel Klimek04616e42012-07-06 05:48:52 +0000989TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000990 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000991 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000992 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000993 EXPECT_TRUE(
994 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000995 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000996 EXPECT_TRUE(
997 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000998 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000999}
1000
1001TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001002 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001003 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001004 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001005 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001006 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001007 EXPECT_TRUE(
1008 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001009 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001010}
1011
1012TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001013 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001014 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001015 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001016 EXPECT_TRUE(
1017 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001018 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001019}
1020
1021TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001022 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001023 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001024 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001025 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001026 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001027}
1028
Manuel Klimekc16c6522013-06-20 13:08:29 +00001029TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1030 EXPECT_TRUE(matches("int x;",
1031 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1032
1033 // Make sure we don't crash on implicit constructors.
1034 EXPECT_TRUE(notMatches("class X {}; X x;",
1035 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1036}
1037
Manuel Klimek04616e42012-07-06 05:48:52 +00001038TEST(Matcher, Call) {
1039 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001040 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001041 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001042
1043 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1044 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1045
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001046 StatementMatcher MethodOnY =
1047 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001048
1049 EXPECT_TRUE(
1050 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1051 MethodOnY));
1052 EXPECT_TRUE(
1053 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1054 MethodOnY));
1055 EXPECT_TRUE(
1056 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1057 MethodOnY));
1058 EXPECT_TRUE(
1059 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1060 MethodOnY));
1061 EXPECT_TRUE(
1062 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1063 MethodOnY));
1064
1065 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001066 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001067
1068 EXPECT_TRUE(
1069 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1070 MethodOnYPointer));
1071 EXPECT_TRUE(
1072 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1073 MethodOnYPointer));
1074 EXPECT_TRUE(
1075 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1076 MethodOnYPointer));
1077 EXPECT_TRUE(
1078 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1079 MethodOnYPointer));
1080 EXPECT_TRUE(
1081 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1082 MethodOnYPointer));
1083}
1084
Daniel Jasper5901e472012-10-01 13:40:41 +00001085TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001086 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001087 lambdaExpr()));
1088}
1089
1090TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001091 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1092 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001093 forRangeStmt()));
1094 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1095 forRangeStmt()));
1096}
1097
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001098TEST(Matcher, SubstNonTypeTemplateParm) {
1099 EXPECT_FALSE(matches("template<int N>\n"
1100 "struct A { static const int n = 0; };\n"
1101 "struct B : public A<42> {};",
1102 substNonTypeTemplateParmExpr()));
1103 EXPECT_TRUE(matches("template<int N>\n"
1104 "struct A { static const int n = N; };\n"
1105 "struct B : public A<42> {};",
1106 substNonTypeTemplateParmExpr()));
1107}
1108
Daniel Jasper5901e472012-10-01 13:40:41 +00001109TEST(Matcher, UserDefinedLiteral) {
1110 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1111 " return i + 1;"
1112 "}"
1113 "char c = 'a'_inc;",
1114 userDefinedLiteral()));
1115}
1116
Daniel Jasper87c3d362012-09-20 14:12:57 +00001117TEST(Matcher, FlowControl) {
1118 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1119 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1120 continueStmt()));
1121 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1122 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1123 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1124}
1125
Daniel Jasper1dad1832012-07-10 20:20:19 +00001126TEST(HasType, MatchesAsString) {
1127 EXPECT_TRUE(
1128 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001129 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001130 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001131 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001132 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001133 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001134 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001135 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001136}
1137
Manuel Klimek04616e42012-07-06 05:48:52 +00001138TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001139 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001140 // Unary operator
1141 EXPECT_TRUE(matches("class Y { }; "
1142 "bool operator!(Y x) { return false; }; "
1143 "Y y; bool c = !y;", OpCall));
1144 // No match -- special operators like "new", "delete"
1145 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1146 // we need to figure out include paths in the test.
1147 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1148 // "class Y { }; "
1149 // "void *operator new(size_t size) { return 0; } "
1150 // "Y *y = new Y;", OpCall));
1151 EXPECT_TRUE(notMatches("class Y { }; "
1152 "void operator delete(void *p) { } "
1153 "void a() {Y *y = new Y; delete y;}", OpCall));
1154 // Binary operator
1155 EXPECT_TRUE(matches("class Y { }; "
1156 "bool operator&&(Y x, Y y) { return true; }; "
1157 "Y a; Y b; bool c = a && b;",
1158 OpCall));
1159 // No match -- normal operator, not an overloaded one.
1160 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1161 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1162}
1163
1164TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1165 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001166 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001167 EXPECT_TRUE(matches("class Y { }; "
1168 "bool operator&&(Y x, Y y) { return true; }; "
1169 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1170 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001171 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001172 EXPECT_TRUE(notMatches("class Y { }; "
1173 "bool operator&&(Y x, Y y) { return true; }; "
1174 "Y a; Y b; bool c = a && b;",
1175 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001176 StatementMatcher OpStarCall =
1177 operatorCallExpr(hasOverloadedOperatorName("*"));
1178 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1179 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001180 DeclarationMatcher ClassWithOpStar =
1181 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1182 EXPECT_TRUE(matches("class Y { int operator*(); };",
1183 ClassWithOpStar));
1184 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1185 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001186 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1187 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1188 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001189}
1190
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001191TEST(Matcher, NestedOverloadedOperatorCalls) {
1192 EXPECT_TRUE(matchAndVerifyResultTrue(
1193 "class Y { }; "
1194 "Y& operator&&(Y& x, Y& y) { return x; }; "
1195 "Y a; Y b; Y c; Y d = a && b && c;",
1196 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1197 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1198 EXPECT_TRUE(matches(
1199 "class Y { }; "
1200 "Y& operator&&(Y& x, Y& y) { return x; }; "
1201 "Y a; Y b; Y c; Y d = a && b && c;",
1202 operatorCallExpr(hasParent(operatorCallExpr()))));
1203 EXPECT_TRUE(matches(
1204 "class Y { }; "
1205 "Y& operator&&(Y& x, Y& y) { return x; }; "
1206 "Y a; Y b; Y c; Y d = a && b && c;",
1207 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1208}
1209
Manuel Klimek04616e42012-07-06 05:48:52 +00001210TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001211 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001212 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001213
1214 EXPECT_TRUE(
1215 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1216 MethodOnY));
1217 EXPECT_TRUE(
1218 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1219 MethodOnY));
1220 EXPECT_TRUE(
1221 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1222 MethodOnY));
1223 EXPECT_TRUE(
1224 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1225 MethodOnY));
1226 EXPECT_TRUE(
1227 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1228 MethodOnY));
1229
1230 EXPECT_TRUE(matches(
1231 "class Y {"
1232 " public: virtual void x();"
1233 "};"
1234 "class X : public Y {"
1235 " public: virtual void x();"
1236 "};"
1237 "void z() { X *x; x->Y::x(); }", MethodOnY));
1238}
1239
1240TEST(Matcher, VariableUsage) {
1241 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001242 declRefExpr(to(
1243 varDecl(hasInitializer(
1244 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001245
1246 EXPECT_TRUE(matches(
1247 "class Y {"
1248 " public:"
1249 " bool x() const;"
1250 "};"
1251 "void z(const Y &y) {"
1252 " bool b = y.x();"
1253 " if (b) {}"
1254 "}", Reference));
1255
1256 EXPECT_TRUE(notMatches(
1257 "class Y {"
1258 " public:"
1259 " bool x() const;"
1260 "};"
1261 "void z(const Y &y) {"
1262 " bool b = y.x();"
1263 "}", Reference));
1264}
1265
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001266TEST(Matcher, VarDecl_Storage) {
1267 auto M = varDecl(hasName("X"), hasLocalStorage());
1268 EXPECT_TRUE(matches("void f() { int X; }", M));
1269 EXPECT_TRUE(notMatches("int X;", M));
1270 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1271
1272 M = varDecl(hasName("X"), hasGlobalStorage());
1273 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1274 EXPECT_TRUE(matches("int X;", M));
1275 EXPECT_TRUE(matches("void f() { static int X; }", M));
1276}
1277
Manuel Klimek61379422012-12-04 14:42:08 +00001278TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001279 EXPECT_TRUE(matches(
1280 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001281 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001282}
1283
Manuel Klimek04616e42012-07-06 05:48:52 +00001284TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001285 StatementMatcher CallOnVariableY =
1286 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001287
1288 EXPECT_TRUE(matches(
1289 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1290 EXPECT_TRUE(matches(
1291 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1292 EXPECT_TRUE(matches(
1293 "class Y { public: void x(); };"
1294 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1295 EXPECT_TRUE(matches(
1296 "class Y { public: void x(); };"
1297 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1298 EXPECT_TRUE(notMatches(
1299 "class Y { public: void x(); };"
1300 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1301 CallOnVariableY));
1302}
1303
Daniel Jasper1dad1832012-07-10 20:20:19 +00001304TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1305 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1306 unaryExprOrTypeTraitExpr()));
1307 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1308 alignOfExpr(anything())));
1309 // FIXME: Uncomment once alignof is enabled.
1310 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1311 // unaryExprOrTypeTraitExpr()));
1312 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1313 // sizeOfExpr()));
1314}
1315
1316TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1317 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1318 hasArgumentOfType(asString("int")))));
1319 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1320 hasArgumentOfType(asString("float")))));
1321 EXPECT_TRUE(matches(
1322 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001323 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001324 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001325 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001326}
1327
Manuel Klimek04616e42012-07-06 05:48:52 +00001328TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001329 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001330}
1331
1332TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001333 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001334}
1335
1336TEST(MemberExpression, MatchesVariable) {
1337 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001338 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001339 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001340 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001341 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001342 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001343}
1344
1345TEST(MemberExpression, MatchesStaticVariable) {
1346 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001347 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001348 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001349 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001350 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001351 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001352}
1353
Daniel Jasper4e566c42012-07-12 08:50:38 +00001354TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001355 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1356 EXPECT_TRUE(matches(
1357 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1358 callExpr(hasArgument(0, declRefExpr(
1359 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001360}
1361
1362TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001363 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001364 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001365 callExpr(hasArgument(0, declRefExpr(
1366 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001367}
1368
Manuel Klimek04616e42012-07-06 05:48:52 +00001369TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1370 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001371 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001372 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001373 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001374 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001375 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001376}
1377
1378TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1379 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001380 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001381 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001382 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001383 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001384 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001385}
1386
1387TEST(IsArrow, MatchesMemberCallsViaArrow) {
1388 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001389 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001390 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001391 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001392 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001393 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001394}
1395
1396TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001397 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001398
1399 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1400 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001401
1402 CallMethodX = callExpr(callee(conversionDecl()));
1403 EXPECT_TRUE(
1404 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1405 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1406 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001407}
1408
1409TEST(Callee, MatchesMemberExpressions) {
1410 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001411 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001412 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001413 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001414}
1415
1416TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001417 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001418
1419 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1420 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1421
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001422 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1423 llvm::Triple::Win32) {
1424 // FIXME: Make this work for MSVC.
1425 // Dependent contexts, but a non-dependent call.
1426 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1427 CallFunctionF));
1428 EXPECT_TRUE(
1429 matches("void f(); template <int N> struct S { void g() { f(); } };",
1430 CallFunctionF));
1431 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001432
1433 // Depedent calls don't match.
1434 EXPECT_TRUE(
1435 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1436 CallFunctionF));
1437 EXPECT_TRUE(
1438 notMatches("void f(int);"
1439 "template <typename T> struct S { void g(T t) { f(t); } };",
1440 CallFunctionF));
1441}
1442
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001443TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1444 EXPECT_TRUE(
1445 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001446 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001447}
1448
1449TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1450 EXPECT_TRUE(
1451 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001452 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001453}
1454
1455TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1456 EXPECT_TRUE(
1457 notMatches("void g(); template <typename T> void f(T t) {}"
1458 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001459 functionTemplateDecl(hasName("f"),
1460 hasDescendant(declRefExpr(to(
1461 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001462}
1463
Manuel Klimek04616e42012-07-06 05:48:52 +00001464TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001465 StatementMatcher CallArgumentY = callExpr(
1466 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001467
1468 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1469 EXPECT_TRUE(
1470 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1471 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1472
Daniel Jasper848cbe12012-09-18 13:09:13 +00001473 StatementMatcher WrongIndex = callExpr(
1474 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001475 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1476}
1477
1478TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001479 StatementMatcher CallArgumentY = callExpr(
1480 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001481 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1482 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1483 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1484}
1485
1486TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001487 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001488
1489 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1490 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1491 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1492}
1493
Daniel Jasper9f501292012-12-04 11:54:27 +00001494TEST(Matcher, ParameterCount) {
1495 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1496 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1497 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1498 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1499 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1500}
1501
Manuel Klimek04616e42012-07-06 05:48:52 +00001502TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001503 DeclarationMatcher ReferenceClassX = varDecl(
1504 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001505 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1506 ReferenceClassX));
1507 EXPECT_TRUE(
1508 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001509 // The match here is on the implicit copy constructor code for
1510 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001511 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001512 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1513 EXPECT_TRUE(
1514 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001515 EXPECT_TRUE(
1516 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1517}
1518
Edwin Vane0a4836e2013-03-06 17:02:57 +00001519TEST(QualType, hasCanonicalType) {
1520 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1521 "int a;"
1522 "int_ref b = a;",
1523 varDecl(hasType(qualType(referenceType())))));
1524 EXPECT_TRUE(
1525 matches("typedef int &int_ref;"
1526 "int a;"
1527 "int_ref b = a;",
1528 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1529}
1530
Edwin Vane119d3df2013-04-02 18:15:55 +00001531TEST(QualType, hasLocalQualifiers) {
1532 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1533 varDecl(hasType(hasLocalQualifiers()))));
1534 EXPECT_TRUE(matches("int *const j = nullptr;",
1535 varDecl(hasType(hasLocalQualifiers()))));
1536 EXPECT_TRUE(matches("int *volatile k;",
1537 varDecl(hasType(hasLocalQualifiers()))));
1538 EXPECT_TRUE(notMatches("int m;",
1539 varDecl(hasType(hasLocalQualifiers()))));
1540}
1541
Manuel Klimek04616e42012-07-06 05:48:52 +00001542TEST(HasParameter, CallsInnerMatcher) {
1543 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001544 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001545 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001546 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001547}
1548
1549TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1550 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001551 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001552}
1553
1554TEST(HasType, MatchesParameterVariableTypesStrictly) {
1555 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001556 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001557 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001558 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001559 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001560 methodDecl(hasParameter(0,
1561 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001562 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001563 methodDecl(hasParameter(0,
1564 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001565}
1566
1567TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1568 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001569 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001570 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001571 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001572}
1573
Daniel Jasper1dad1832012-07-10 20:20:19 +00001574TEST(Returns, MatchesReturnTypes) {
1575 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001576 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001577 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001578 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001579 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001580 functionDecl(returns(hasDeclaration(
1581 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001582}
1583
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001584TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001585 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1586 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1587 functionDecl(isExternC())));
1588 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001589}
1590
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001591TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1592 EXPECT_TRUE(
1593 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1594 EXPECT_TRUE(matches("void Func() = delete;",
1595 functionDecl(hasName("Func"), isDeleted())));
1596}
1597
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001598TEST(isConstexpr, MatchesConstexprDeclarations) {
1599 EXPECT_TRUE(matches("constexpr int foo = 42;",
1600 varDecl(hasName("foo"), isConstexpr())));
1601 EXPECT_TRUE(matches("constexpr int bar();",
1602 functionDecl(hasName("bar"), isConstexpr())));
1603}
1604
Manuel Klimek04616e42012-07-06 05:48:52 +00001605TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1606 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001607 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001608}
1609
1610TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1611 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001612 methodDecl(hasAnyParameter(hasType(pointsTo(
1613 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001614}
1615
Alp Toker8db6e7a2014-01-05 06:38:57 +00001616TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001617 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001618 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001619 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001620 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001621}
1622
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001623TEST(Matcher, MatchesClassTemplateSpecialization) {
1624 EXPECT_TRUE(matches("template<typename T> struct A {};"
1625 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001626 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001627 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001628 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001629 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001630 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001631}
1632
Manuel Klimekc16c6522013-06-20 13:08:29 +00001633TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1634 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1635 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1636}
1637
1638TEST(ParmVarDecl, MatchesParmVars) {
1639 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1640 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1641}
1642
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001643TEST(Matcher, MatchesTypeTemplateArgument) {
1644 EXPECT_TRUE(matches(
1645 "template<typename T> struct B {};"
1646 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001647 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001648 asString("int"))))));
1649}
1650
1651TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1652 EXPECT_TRUE(matches(
1653 "struct B { int next; };"
1654 "template<int(B::*next_ptr)> struct A {};"
1655 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001656 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1657 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001658
1659 EXPECT_TRUE(notMatches(
1660 "template <typename T> struct A {};"
1661 "A<int> a;",
1662 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1663 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001664
1665 EXPECT_TRUE(matches(
1666 "struct B { int next; };"
1667 "template<int(B::*next_ptr)> struct A {};"
1668 "A<&B::next> a;",
1669 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1670 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1671
1672 EXPECT_TRUE(notMatches(
1673 "template <typename T> struct A {};"
1674 "A<int> a;",
1675 templateSpecializationType(hasAnyTemplateArgument(
1676 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001677}
1678
1679TEST(Matcher, MatchesSpecificArgument) {
1680 EXPECT_TRUE(matches(
1681 "template<typename T, typename U> class A {};"
1682 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001683 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001684 1, refersToType(asString("int"))))));
1685 EXPECT_TRUE(notMatches(
1686 "template<typename T, typename U> class A {};"
1687 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001688 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001689 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001690
1691 EXPECT_TRUE(matches(
1692 "template<typename T, typename U> class A {};"
1693 "A<bool, int> a;",
1694 templateSpecializationType(hasTemplateArgument(
1695 1, refersToType(asString("int"))))));
1696 EXPECT_TRUE(notMatches(
1697 "template<typename T, typename U> class A {};"
1698 "A<int, bool> a;",
1699 templateSpecializationType(hasTemplateArgument(
1700 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001701}
1702
Manuel Klimek7735e402014-10-09 13:06:22 +00001703TEST(TemplateArgument, Matches) {
1704 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1705 classTemplateSpecializationDecl(
1706 hasAnyTemplateArgument(templateArgument()))));
1707 EXPECT_TRUE(matches(
1708 "template<typename T> struct C {}; C<int> c;",
1709 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1710}
1711
1712TEST(TemplateArgumentCountIs, Matches) {
1713 EXPECT_TRUE(
1714 matches("template<typename T> struct C {}; C<int> c;",
1715 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1716 EXPECT_TRUE(
1717 notMatches("template<typename T> struct C {}; C<int> c;",
1718 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1719
1720 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1721 templateSpecializationType(templateArgumentCountIs(1))));
1722 EXPECT_TRUE(
1723 notMatches("template<typename T> struct C {}; C<int> c;",
1724 templateSpecializationType(templateArgumentCountIs(2))));
1725}
1726
1727TEST(IsIntegral, Matches) {
1728 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1729 classTemplateSpecializationDecl(
1730 hasAnyTemplateArgument(isIntegral()))));
1731 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1732 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1733 templateArgument(isIntegral())))));
1734}
1735
1736TEST(RefersToIntegralType, Matches) {
1737 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1738 classTemplateSpecializationDecl(
1739 hasAnyTemplateArgument(refersToIntegralType(
1740 asString("int"))))));
1741 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1742 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1743 refersToIntegralType(asString("int"))))));
1744}
1745
1746TEST(EqualsIntegralValue, Matches) {
1747 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1748 classTemplateSpecializationDecl(
1749 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1750 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1751 classTemplateSpecializationDecl(
1752 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1753 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1754 classTemplateSpecializationDecl(
1755 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1756 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1757 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1758 equalsIntegralValue("0042")))));
1759}
1760
Daniel Jasper639522c2013-02-25 12:02:08 +00001761TEST(Matcher, MatchesAccessSpecDecls) {
1762 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1763 EXPECT_TRUE(
1764 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1765 EXPECT_TRUE(
1766 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1767 EXPECT_TRUE(
1768 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1769
1770 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1771}
1772
Edwin Vane37ee1d72013-04-09 20:46:36 +00001773TEST(Matcher, MatchesVirtualMethod) {
1774 EXPECT_TRUE(matches("class X { virtual int f(); };",
1775 methodDecl(isVirtual(), hasName("::X::f"))));
1776 EXPECT_TRUE(notMatches("class X { int f(); };",
1777 methodDecl(isVirtual())));
1778}
1779
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001780TEST(Matcher, MatchesPureMethod) {
1781 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1782 methodDecl(isPure(), hasName("::X::f"))));
1783 EXPECT_TRUE(notMatches("class X { int f(); };",
1784 methodDecl(isPure())));
1785}
1786
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001787TEST(Matcher, MatchesConstMethod) {
1788 EXPECT_TRUE(matches("struct A { void foo() const; };",
1789 methodDecl(isConst())));
1790 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1791 methodDecl(isConst())));
1792}
1793
Edwin Vane37ee1d72013-04-09 20:46:36 +00001794TEST(Matcher, MatchesOverridingMethod) {
1795 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1796 "class Y : public X { int f(); };",
1797 methodDecl(isOverride(), hasName("::Y::f"))));
1798 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1799 "class Y : public X { int f(); };",
1800 methodDecl(isOverride(), hasName("::X::f"))));
1801 EXPECT_TRUE(notMatches("class X { int f(); }; "
1802 "class Y : public X { int f(); };",
1803 methodDecl(isOverride())));
1804 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1805 methodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001806 EXPECT_TRUE(
1807 matches("template <typename Base> struct Y : Base { void f() override;};",
1808 methodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001809}
1810
Manuel Klimek04616e42012-07-06 05:48:52 +00001811TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001812 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001813
1814 EXPECT_TRUE(
1815 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1816 EXPECT_TRUE(
1817 matches("class X { public: X(); }; void x() { X x = X(); }",
1818 Constructor));
1819 EXPECT_TRUE(
1820 matches("class X { public: X(int); }; void x() { X x = 0; }",
1821 Constructor));
1822 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1823}
1824
1825TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001826 StatementMatcher Constructor = constructExpr(
1827 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001828
1829 EXPECT_TRUE(
1830 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1831 Constructor));
1832 EXPECT_TRUE(
1833 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1834 Constructor));
1835 EXPECT_TRUE(
1836 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1837 Constructor));
1838 EXPECT_TRUE(
1839 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1840 Constructor));
1841
Daniel Jasper848cbe12012-09-18 13:09:13 +00001842 StatementMatcher WrongIndex = constructExpr(
1843 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001844 EXPECT_TRUE(
1845 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1846 WrongIndex));
1847}
1848
1849TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001850 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001851
1852 EXPECT_TRUE(
1853 matches("class X { public: X(int); }; void x() { X x(0); }",
1854 Constructor1Arg));
1855 EXPECT_TRUE(
1856 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1857 Constructor1Arg));
1858 EXPECT_TRUE(
1859 matches("class X { public: X(int); }; void x() { X x = 0; }",
1860 Constructor1Arg));
1861 EXPECT_TRUE(
1862 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1863 Constructor1Arg));
1864}
1865
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001866TEST(Matcher, ConstructorListInitialization) {
1867 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1868
1869 EXPECT_TRUE(
1870 matches("class X { public: X(int); }; void x() { X x{0}; }",
1871 ConstructorListInit));
1872 EXPECT_FALSE(
1873 matches("class X { public: X(int); }; void x() { X x(0); }",
1874 ConstructorListInit));
1875}
1876
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001877TEST(Matcher,ThisExpr) {
1878 EXPECT_TRUE(
1879 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1880 EXPECT_TRUE(
1881 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1882}
1883
Manuel Klimek04616e42012-07-06 05:48:52 +00001884TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001885 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001886
1887 std::string ClassString = "class string { public: string(); ~string(); }; ";
1888
1889 EXPECT_TRUE(
1890 matches(ClassString +
1891 "string GetStringByValue();"
1892 "void FunctionTakesString(string s);"
1893 "void run() { FunctionTakesString(GetStringByValue()); }",
1894 TempExpression));
1895
1896 EXPECT_TRUE(
1897 notMatches(ClassString +
1898 "string* GetStringPointer(); "
1899 "void FunctionTakesStringPtr(string* s);"
1900 "void run() {"
1901 " string* s = GetStringPointer();"
1902 " FunctionTakesStringPtr(GetStringPointer());"
1903 " FunctionTakesStringPtr(s);"
1904 "}",
1905 TempExpression));
1906
1907 EXPECT_TRUE(
1908 notMatches("class no_dtor {};"
1909 "no_dtor GetObjByValue();"
1910 "void ConsumeObj(no_dtor param);"
1911 "void run() { ConsumeObj(GetObjByValue()); }",
1912 TempExpression));
1913}
1914
Sam Panzer68a35af2012-08-24 22:04:44 +00001915TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1916 std::string ClassString =
1917 "class string { public: string(); int length(); }; ";
1918
1919 EXPECT_TRUE(
1920 matches(ClassString +
1921 "string GetStringByValue();"
1922 "void FunctionTakesString(string s);"
1923 "void run() { FunctionTakesString(GetStringByValue()); }",
1924 materializeTemporaryExpr()));
1925
1926 EXPECT_TRUE(
1927 notMatches(ClassString +
1928 "string* GetStringPointer(); "
1929 "void FunctionTakesStringPtr(string* s);"
1930 "void run() {"
1931 " string* s = GetStringPointer();"
1932 " FunctionTakesStringPtr(GetStringPointer());"
1933 " FunctionTakesStringPtr(s);"
1934 "}",
1935 materializeTemporaryExpr()));
1936
1937 EXPECT_TRUE(
1938 notMatches(ClassString +
1939 "string GetStringByValue();"
1940 "void run() { int k = GetStringByValue().length(); }",
1941 materializeTemporaryExpr()));
1942
1943 EXPECT_TRUE(
1944 notMatches(ClassString +
1945 "string GetStringByValue();"
1946 "void run() { GetStringByValue(); }",
1947 materializeTemporaryExpr()));
1948}
1949
Manuel Klimek04616e42012-07-06 05:48:52 +00001950TEST(ConstructorDeclaration, SimpleCase) {
1951 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001952 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001953 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001954 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001955}
1956
1957TEST(ConstructorDeclaration, IsImplicit) {
1958 // This one doesn't match because the constructor is not added by the
1959 // compiler (it is not needed).
1960 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001961 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001962 // The compiler added the implicit default constructor.
1963 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001964 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001965 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001966 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001967 // The compiler added an implicit assignment operator.
1968 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1969 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001970}
1971
Daniel Jasper1dad1832012-07-10 20:20:19 +00001972TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1973 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001974 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001975}
1976
1977TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001978 EXPECT_TRUE(notMatches("class Foo {};",
1979 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001980}
1981
Manuel Klimek04616e42012-07-06 05:48:52 +00001982TEST(HasAnyConstructorInitializer, SimpleCase) {
1983 EXPECT_TRUE(notMatches(
1984 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001985 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001986 EXPECT_TRUE(matches(
1987 "class Foo {"
1988 " Foo() : foo_() { }"
1989 " int foo_;"
1990 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001991 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001992}
1993
1994TEST(HasAnyConstructorInitializer, ForField) {
1995 static const char Code[] =
1996 "class Baz { };"
1997 "class Foo {"
1998 " Foo() : foo_() { }"
1999 " Baz foo_;"
2000 " Baz bar_;"
2001 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002002 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
2003 forField(hasType(recordDecl(hasName("Baz"))))))));
2004 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002005 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002006 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
2007 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002008}
2009
2010TEST(HasAnyConstructorInitializer, WithInitializer) {
2011 static const char Code[] =
2012 "class Foo {"
2013 " Foo() : foo_(0) { }"
2014 " int foo_;"
2015 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002016 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002017 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002018 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002019 withInitializer(integerLiteral(equals(1)))))));
2020}
2021
2022TEST(HasAnyConstructorInitializer, IsWritten) {
2023 static const char Code[] =
2024 "struct Bar { Bar(){} };"
2025 "class Foo {"
2026 " Foo() : foo_() { }"
2027 " Bar foo_;"
2028 " Bar bar_;"
2029 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002030 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002031 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002032 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002033 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002034 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002035 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2036}
2037
2038TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002039 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002040
2041 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2042 EXPECT_TRUE(
2043 matches("class X { public: X(); }; void x() { new X(); }", New));
2044 EXPECT_TRUE(
2045 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2046 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2047}
2048
2049TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002050 StatementMatcher New = constructExpr(
2051 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002052
2053 EXPECT_TRUE(
2054 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2055 New));
2056 EXPECT_TRUE(
2057 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2058 New));
2059 EXPECT_TRUE(
2060 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2061 New));
2062
Daniel Jasper848cbe12012-09-18 13:09:13 +00002063 StatementMatcher WrongIndex = constructExpr(
2064 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002065 EXPECT_TRUE(
2066 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2067 WrongIndex));
2068}
2069
2070TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002071 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002072
2073 EXPECT_TRUE(
2074 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2075 EXPECT_TRUE(
2076 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2077 New));
2078}
2079
Daniel Jasper1dad1832012-07-10 20:20:19 +00002080TEST(Matcher, DeleteExpression) {
2081 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002082 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002083}
2084
Manuel Klimek04616e42012-07-06 05:48:52 +00002085TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002086 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002087
2088 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2089 EXPECT_TRUE(
2090 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2091 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2092}
2093
2094TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002095 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002096 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2097 // wide string
2098 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2099 // with escaped characters
2100 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2101 // no matching -- though the data type is the same, there is no string literal
2102 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2103}
2104
2105TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002106 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002107 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2108 // wide character
2109 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2110 // wide character, Hex encoded, NOT MATCHED!
2111 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2112 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2113}
2114
2115TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002116 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002117 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2118 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2119 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2120 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2121
2122 // Non-matching cases (character literals, float and double)
2123 EXPECT_TRUE(notMatches("int i = L'a';",
2124 HasIntLiteral)); // this is actually a character
2125 // literal cast to int
2126 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2127 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2128 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2129}
2130
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002131TEST(Matcher, FloatLiterals) {
2132 StatementMatcher HasFloatLiteral = floatLiteral();
2133 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2134 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2135 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2136 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2137 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002138 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2139 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2140 EXPECT_TRUE(
2141 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002142
2143 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002144 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2145 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2146 EXPECT_TRUE(
2147 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002148}
2149
Daniel Jasper5901e472012-10-01 13:40:41 +00002150TEST(Matcher, NullPtrLiteral) {
2151 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2152}
2153
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002154TEST(Matcher, GNUNullExpr) {
2155 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2156}
2157
Daniel Jasper87c3d362012-09-20 14:12:57 +00002158TEST(Matcher, AsmStatement) {
2159 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2160}
2161
Manuel Klimek04616e42012-07-06 05:48:52 +00002162TEST(Matcher, Conditions) {
2163 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2164
2165 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2166 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2167 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2168 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2169 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2170}
2171
Manuel Klimek909b5c942014-05-27 10:04:12 +00002172TEST(IfStmt, ChildTraversalMatchers) {
2173 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2174 ifStmt(hasThen(boolLiteral(equals(true))))));
2175 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2176 ifStmt(hasThen(boolLiteral(equals(true))))));
2177 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2178 ifStmt(hasElse(boolLiteral(equals(true))))));
2179 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2180 ifStmt(hasElse(boolLiteral(equals(true))))));
2181}
2182
Manuel Klimek04616e42012-07-06 05:48:52 +00002183TEST(MatchBinaryOperator, HasOperatorName) {
2184 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2185
2186 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2187 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2188}
2189
2190TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2191 StatementMatcher OperatorTrueFalse =
2192 binaryOperator(hasLHS(boolLiteral(equals(true))),
2193 hasRHS(boolLiteral(equals(false))));
2194
2195 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2196 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2197 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2198}
2199
2200TEST(MatchBinaryOperator, HasEitherOperand) {
2201 StatementMatcher HasOperand =
2202 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2203
2204 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2205 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2206 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2207}
2208
2209TEST(Matcher, BinaryOperatorTypes) {
2210 // Integration test that verifies the AST provides all binary operators in
2211 // a way we expect.
2212 // FIXME: Operator ','
2213 EXPECT_TRUE(
2214 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2215 EXPECT_TRUE(
2216 matches("bool b; bool c = (b = true);",
2217 binaryOperator(hasOperatorName("="))));
2218 EXPECT_TRUE(
2219 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2220 EXPECT_TRUE(
2221 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2222 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2223 EXPECT_TRUE(
2224 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2225 EXPECT_TRUE(
2226 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2227 EXPECT_TRUE(
2228 matches("int i = 1; int j = (i <<= 2);",
2229 binaryOperator(hasOperatorName("<<="))));
2230 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2231 EXPECT_TRUE(
2232 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2233 EXPECT_TRUE(
2234 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2235 EXPECT_TRUE(
2236 matches("int i = 1; int j = (i >>= 2);",
2237 binaryOperator(hasOperatorName(">>="))));
2238 EXPECT_TRUE(
2239 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2240 EXPECT_TRUE(
2241 matches("int i = 42; int j = (i ^= 42);",
2242 binaryOperator(hasOperatorName("^="))));
2243 EXPECT_TRUE(
2244 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2245 EXPECT_TRUE(
2246 matches("int i = 42; int j = (i %= 42);",
2247 binaryOperator(hasOperatorName("%="))));
2248 EXPECT_TRUE(
2249 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2250 EXPECT_TRUE(
2251 matches("bool b = true && false;",
2252 binaryOperator(hasOperatorName("&&"))));
2253 EXPECT_TRUE(
2254 matches("bool b = true; bool c = (b &= false);",
2255 binaryOperator(hasOperatorName("&="))));
2256 EXPECT_TRUE(
2257 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2258 EXPECT_TRUE(
2259 matches("bool b = true || false;",
2260 binaryOperator(hasOperatorName("||"))));
2261 EXPECT_TRUE(
2262 matches("bool b = true; bool c = (b |= false);",
2263 binaryOperator(hasOperatorName("|="))));
2264 EXPECT_TRUE(
2265 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2266 EXPECT_TRUE(
2267 matches("int i = 42; int j = (i *= 23);",
2268 binaryOperator(hasOperatorName("*="))));
2269 EXPECT_TRUE(
2270 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2271 EXPECT_TRUE(
2272 matches("int i = 42; int j = (i /= 23);",
2273 binaryOperator(hasOperatorName("/="))));
2274 EXPECT_TRUE(
2275 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2276 EXPECT_TRUE(
2277 matches("int i = 42; int j = (i += 23);",
2278 binaryOperator(hasOperatorName("+="))));
2279 EXPECT_TRUE(
2280 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2281 EXPECT_TRUE(
2282 matches("int i = 42; int j = (i -= 23);",
2283 binaryOperator(hasOperatorName("-="))));
2284 EXPECT_TRUE(
2285 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2286 binaryOperator(hasOperatorName("->*"))));
2287 EXPECT_TRUE(
2288 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2289 binaryOperator(hasOperatorName(".*"))));
2290
2291 // Member expressions as operators are not supported in matches.
2292 EXPECT_TRUE(
2293 notMatches("struct A { void x(A *a) { a->x(this); } };",
2294 binaryOperator(hasOperatorName("->"))));
2295
2296 // Initializer assignments are not represented as operator equals.
2297 EXPECT_TRUE(
2298 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2299
2300 // Array indexing is not represented as operator.
2301 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2302
2303 // Overloaded operators do not match at all.
2304 EXPECT_TRUE(notMatches(
2305 "struct A { bool operator&&(const A &a) const { return false; } };"
2306 "void x() { A a, b; a && b; }",
2307 binaryOperator()));
2308}
2309
2310TEST(MatchUnaryOperator, HasOperatorName) {
2311 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2312
2313 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2314 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2315}
2316
2317TEST(MatchUnaryOperator, HasUnaryOperand) {
2318 StatementMatcher OperatorOnFalse =
2319 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2320
2321 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2322 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2323}
2324
2325TEST(Matcher, UnaryOperatorTypes) {
2326 // Integration test that verifies the AST provides all unary operators in
2327 // a way we expect.
2328 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2329 EXPECT_TRUE(
2330 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2331 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2332 EXPECT_TRUE(
2333 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2334 EXPECT_TRUE(
2335 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2336 EXPECT_TRUE(
2337 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2338 EXPECT_TRUE(
2339 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2340 EXPECT_TRUE(
2341 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2342 EXPECT_TRUE(
2343 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2344 EXPECT_TRUE(
2345 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2346
2347 // We don't match conversion operators.
2348 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2349
2350 // Function calls are not represented as operator.
2351 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2352
2353 // Overloaded operators do not match at all.
2354 // FIXME: We probably want to add that.
2355 EXPECT_TRUE(notMatches(
2356 "struct A { bool operator!() const { return false; } };"
2357 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2358}
2359
2360TEST(Matcher, ConditionalOperator) {
2361 StatementMatcher Conditional = conditionalOperator(
2362 hasCondition(boolLiteral(equals(true))),
2363 hasTrueExpression(boolLiteral(equals(false))));
2364
2365 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2366 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2367 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2368
2369 StatementMatcher ConditionalFalse = conditionalOperator(
2370 hasFalseExpression(boolLiteral(equals(false))));
2371
2372 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2373 EXPECT_TRUE(
2374 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2375}
2376
Daniel Jasper1dad1832012-07-10 20:20:19 +00002377TEST(ArraySubscriptMatchers, ArraySubscripts) {
2378 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2379 arraySubscriptExpr()));
2380 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2381 arraySubscriptExpr()));
2382}
2383
2384TEST(ArraySubscriptMatchers, ArrayIndex) {
2385 EXPECT_TRUE(matches(
2386 "int i[2]; void f() { i[1] = 1; }",
2387 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2388 EXPECT_TRUE(matches(
2389 "int i[2]; void f() { 1[i] = 1; }",
2390 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2391 EXPECT_TRUE(notMatches(
2392 "int i[2]; void f() { i[1] = 1; }",
2393 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2394}
2395
2396TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2397 EXPECT_TRUE(matches(
2398 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002399 arraySubscriptExpr(hasBase(implicitCastExpr(
2400 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002401}
2402
Manuel Klimek04616e42012-07-06 05:48:52 +00002403TEST(Matcher, HasNameSupportsNamespaces) {
2404 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002405 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002406 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002407 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002408 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002409 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002410 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002411 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002412 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002413 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002414 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002415 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002416 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002417 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002418 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002419 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002420 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002421 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002422 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002423 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002424 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002425 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002426 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002427 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002428}
2429
2430TEST(Matcher, HasNameSupportsOuterClasses) {
2431 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002432 matches("class A { class B { class C; }; };",
2433 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002434 EXPECT_TRUE(
2435 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002436 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002437 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002438 matches("class A { class B { class C; }; };",
2439 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002440 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002441 matches("class A { class B { class C; }; };",
2442 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002443 EXPECT_TRUE(
2444 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002445 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002446 EXPECT_TRUE(
2447 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002448 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002449 EXPECT_TRUE(
2450 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002451 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002452 EXPECT_TRUE(
2453 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002454 recordDecl(hasName("::C"))));
2455 EXPECT_TRUE(
2456 notMatches("class A { class B { class C; }; };",
2457 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002458 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002459 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002460 EXPECT_TRUE(
2461 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002462 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002463}
2464
2465TEST(Matcher, IsDefinition) {
2466 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002467 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002468 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2469 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2470
2471 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002472 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002473 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2474 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2475
2476 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002477 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002478 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2479 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2480}
2481
2482TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002483 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002484 ofClass(hasName("X")))));
2485
2486 EXPECT_TRUE(
2487 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2488 EXPECT_TRUE(
2489 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2490 Constructor));
2491 EXPECT_TRUE(
2492 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2493 Constructor));
2494}
2495
2496TEST(Matcher, VisitsTemplateInstantiations) {
2497 EXPECT_TRUE(matches(
2498 "class A { public: void x(); };"
2499 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002500 "void f() { B<A> b; b.y(); }",
2501 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002502
2503 EXPECT_TRUE(matches(
2504 "class A { public: void x(); };"
2505 "class C {"
2506 " public:"
2507 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2508 "};"
2509 "void f() {"
2510 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002511 "}",
2512 recordDecl(hasName("C"),
2513 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002514}
2515
Daniel Jasper1dad1832012-07-10 20:20:19 +00002516TEST(Matcher, HandlesNullQualTypes) {
2517 // FIXME: Add a Type matcher so we can replace uses of this
2518 // variable with Type(True())
2519 const TypeMatcher AnyType = anything();
2520
2521 // We don't really care whether this matcher succeeds; we're testing that
2522 // it completes without crashing.
2523 EXPECT_TRUE(matches(
2524 "struct A { };"
2525 "template <typename T>"
2526 "void f(T t) {"
2527 " T local_t(t /* this becomes a null QualType in the AST */);"
2528 "}"
2529 "void g() {"
2530 " f(0);"
2531 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002532 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002533 anyOf(
2534 TypeMatcher(hasDeclaration(anything())),
2535 pointsTo(AnyType),
2536 references(AnyType)
2537 // Other QualType matchers should go here.
2538 ))))));
2539}
2540
Manuel Klimek04616e42012-07-06 05:48:52 +00002541// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002542AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002543 // Make sure all special variables are used: node, match_finder,
2544 // bound_nodes_builder, and the parameter named 'AMatcher'.
2545 return AMatcher.matches(Node, Finder, Builder);
2546}
2547
2548TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002549 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002550
2551 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002552 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002553
2554 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002555 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002556
2557 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002558 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002559}
2560
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002561AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2562 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2563 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002564 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002565 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002566 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2567 ASTMatchFinder::BK_First);
2568}
2569
2570TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002571 DeclarationMatcher HasClassB =
2572 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002573
2574 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002575 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002576
2577 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002578 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002579
2580 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002581 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002582
2583 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002584 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002585
2586 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2587}
2588
2589TEST(For, FindsForLoops) {
2590 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2591 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002592 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2593 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002594 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002595}
2596
Daniel Jasper4e566c42012-07-12 08:50:38 +00002597TEST(For, ForLoopInternals) {
2598 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2599 forStmt(hasCondition(anything()))));
2600 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2601 forStmt(hasLoopInit(anything()))));
2602}
2603
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002604TEST(For, ForRangeLoopInternals) {
2605 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2606 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002607 EXPECT_TRUE(matches(
2608 "void f(){ int a[] {1, 2}; for (int i : a); }",
2609 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002610}
2611
Daniel Jasper4e566c42012-07-12 08:50:38 +00002612TEST(For, NegativeForLoopInternals) {
2613 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002614 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002615 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2616 forStmt(hasLoopInit(anything()))));
2617}
2618
Manuel Klimek04616e42012-07-06 05:48:52 +00002619TEST(For, ReportsNoFalsePositives) {
2620 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2621 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2622}
2623
2624TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002625 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2626 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2627 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002628}
2629
2630TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2631 // It's not a compound statement just because there's "{}" in the source
2632 // text. This is an AST search, not grep.
2633 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002634 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002635 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002636 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002637}
2638
Daniel Jasper4e566c42012-07-12 08:50:38 +00002639TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002640 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002641 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002642 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002643 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002644 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002645 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002646 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002647 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002648 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2649 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002650}
2651
2652TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2653 // The simplest case: every compound statement is in a function
2654 // definition, and the function body itself must be a compound
2655 // statement.
2656 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002657 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002658}
2659
2660TEST(HasAnySubstatement, IsNotRecursive) {
2661 // It's really "has any immediate substatement".
2662 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002663 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002664}
2665
2666TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2667 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002668 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002669}
2670
2671TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2672 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002673 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002674}
2675
2676TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2677 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002678 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002679 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002680 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002681}
2682
2683TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2684 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002685 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002686 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002687 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002688 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002689 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002690}
2691
2692TEST(StatementCountIs, WorksWithMultipleStatements) {
2693 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002694 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002695}
2696
2697TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2698 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002699 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002700 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002701 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002702 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002703 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002704 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002705 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002706}
2707
2708TEST(Member, WorksInSimplestCase) {
2709 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002710 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002711}
2712
2713TEST(Member, DoesNotMatchTheBaseExpression) {
2714 // Don't pick out the wrong part of the member expression, this should
2715 // be checking the member (name) only.
2716 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002717 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002718}
2719
2720TEST(Member, MatchesInMemberFunctionCall) {
2721 EXPECT_TRUE(matches("void f() {"
2722 " struct { void first() {}; } s;"
2723 " s.first();"
2724 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002725 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002726}
2727
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002728TEST(Member, MatchesMember) {
2729 EXPECT_TRUE(matches(
2730 "struct A { int i; }; void f() { A a; a.i = 2; }",
2731 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2732 EXPECT_TRUE(notMatches(
2733 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2734 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2735}
2736
Daniel Jasper639522c2013-02-25 12:02:08 +00002737TEST(Member, UnderstandsAccess) {
2738 EXPECT_TRUE(matches(
2739 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2740 EXPECT_TRUE(notMatches(
2741 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2742 EXPECT_TRUE(notMatches(
2743 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2744
2745 EXPECT_TRUE(notMatches(
2746 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2747 EXPECT_TRUE(notMatches(
2748 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2749 EXPECT_TRUE(matches(
2750 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2751
2752 EXPECT_TRUE(notMatches(
2753 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2754 EXPECT_TRUE(matches("class A { protected: int i; };",
2755 fieldDecl(isProtected(), hasName("i"))));
2756 EXPECT_TRUE(notMatches(
2757 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2758
2759 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2760 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2761 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2762 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2763}
2764
Dmitri Gribenko06963042012-08-18 00:29:27 +00002765TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002766 // Fails in C++11 mode
2767 EXPECT_TRUE(matchesConditionally(
2768 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2769 "class X { void *operator new(std::size_t); };",
2770 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002771
2772 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002773 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002774
Daniel Jasper5901e472012-10-01 13:40:41 +00002775 // Fails in C++11 mode
2776 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002777 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2778 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002779 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002780}
2781
Manuel Klimek04616e42012-07-06 05:48:52 +00002782TEST(HasObjectExpression, DoesNotMatchMember) {
2783 EXPECT_TRUE(notMatches(
2784 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002785 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002786}
2787
2788TEST(HasObjectExpression, MatchesBaseOfVariable) {
2789 EXPECT_TRUE(matches(
2790 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002791 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002792 EXPECT_TRUE(matches(
2793 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002794 memberExpr(hasObjectExpression(
2795 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002796}
2797
2798TEST(HasObjectExpression,
2799 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2800 EXPECT_TRUE(matches(
2801 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002802 memberExpr(hasObjectExpression(
2803 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002804 EXPECT_TRUE(matches(
2805 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002806 memberExpr(hasObjectExpression(
2807 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002808}
2809
2810TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002811 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2812 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2813 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2814 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002815}
2816
2817TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002818 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002819}
2820
2821TEST(IsConstQualified, MatchesConstInt) {
2822 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002823 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002824}
2825
2826TEST(IsConstQualified, MatchesConstPointer) {
2827 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002828 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002829}
2830
2831TEST(IsConstQualified, MatchesThroughTypedef) {
2832 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002833 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002834 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002835 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002836}
2837
2838TEST(IsConstQualified, DoesNotMatchInappropriately) {
2839 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002840 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002841 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002842 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002843}
2844
Sam Panzer80c13772012-08-16 16:58:10 +00002845TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002846 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2847 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2848 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2849 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002850}
2851TEST(CastExpression, MatchesImplicitCasts) {
2852 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002853 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002854 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002855 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002856}
2857
2858TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002859 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2860 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2861 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2862 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002863}
2864
Manuel Klimek04616e42012-07-06 05:48:52 +00002865TEST(ReinterpretCast, MatchesSimpleCase) {
2866 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002867 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002868}
2869
2870TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002871 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002872 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002873 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002874 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002875 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002876 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2877 "B b;"
2878 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002879 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002880}
2881
2882TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002883 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002884 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002885 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002886}
2887
2888TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002889 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002890 EXPECT_TRUE(
2891 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002892 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002893 EXPECT_TRUE(
2894 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002895 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002896}
2897
2898TEST(DynamicCast, MatchesSimpleCase) {
2899 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2900 "B b;"
2901 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002902 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002903}
2904
2905TEST(StaticCast, MatchesSimpleCase) {
2906 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002907 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002908}
2909
2910TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002911 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002912 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002913 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002914 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002915 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002916 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2917 "B b;"
2918 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002919 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002920}
2921
Daniel Jasper417f7762012-09-18 13:36:17 +00002922TEST(CStyleCast, MatchesSimpleCase) {
2923 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2924}
2925
2926TEST(CStyleCast, DoesNotMatchOtherCasts) {
2927 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2928 "char q, *r = const_cast<char*>(&q);"
2929 "void* s = reinterpret_cast<char*>(&s);"
2930 "struct B { virtual ~B() {} }; struct D : B {};"
2931 "B b;"
2932 "D* t = dynamic_cast<D*>(&b);",
2933 cStyleCastExpr()));
2934}
2935
Manuel Klimek04616e42012-07-06 05:48:52 +00002936TEST(HasDestinationType, MatchesSimpleCase) {
2937 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002938 staticCastExpr(hasDestinationType(
2939 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002940}
2941
Sam Panzer80c13772012-08-16 16:58:10 +00002942TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2943 // This test creates an implicit const cast.
2944 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002945 implicitCastExpr(
2946 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002947 // This test creates an implicit array-to-pointer cast.
2948 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002949 implicitCastExpr(hasImplicitDestinationType(
2950 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002951}
2952
2953TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2954 // This test creates an implicit cast from int to char.
2955 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002956 implicitCastExpr(hasImplicitDestinationType(
2957 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002958 // This test creates an implicit array-to-pointer cast.
2959 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002960 implicitCastExpr(hasImplicitDestinationType(
2961 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002962}
2963
2964TEST(ImplicitCast, MatchesSimpleCase) {
2965 // This test creates an implicit const cast.
2966 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002967 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002968 // This test creates an implicit cast from int to char.
2969 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002970 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002971 // This test creates an implicit array-to-pointer cast.
2972 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002973 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002974}
2975
2976TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002977 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002978 // are present, and that it ignores explicit and paren casts.
2979
2980 // These two test cases have no casts.
2981 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002982 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002983 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002984 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002985
2986 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002987 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002988 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002989 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002990
2991 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002992 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002993}
2994
2995TEST(IgnoringImpCasts, MatchesImpCasts) {
2996 // This test checks that ignoringImpCasts matches when implicit casts are
2997 // present and its inner matcher alone does not match.
2998 // Note that this test creates an implicit const cast.
2999 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003000 varDecl(hasInitializer(ignoringImpCasts(
3001 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003002 // This test creates an implict cast from int to char.
3003 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003004 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003005 integerLiteral(equals(0)))))));
3006}
3007
3008TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3009 // These tests verify that ignoringImpCasts does not match if the inner
3010 // matcher does not match.
3011 // Note that the first test creates an implicit const cast.
3012 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003013 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003014 unless(anything()))))));
3015 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003016 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003017 unless(anything()))))));
3018
3019 // These tests verify that ignoringImplictCasts does not look through explicit
3020 // casts or parentheses.
3021 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003022 varDecl(hasInitializer(ignoringImpCasts(
3023 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003024 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003025 varDecl(hasInitializer(ignoringImpCasts(
3026 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003027 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003028 varDecl(hasInitializer(ignoringImpCasts(
3029 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003030 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003031 varDecl(hasInitializer(ignoringImpCasts(
3032 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003033}
3034
3035TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3036 // This test verifies that expressions that do not have implicit casts
3037 // still match the inner matcher.
3038 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003039 varDecl(hasInitializer(ignoringImpCasts(
3040 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003041}
3042
3043TEST(IgnoringParenCasts, MatchesParenCasts) {
3044 // This test checks that ignoringParenCasts matches when parentheses and/or
3045 // casts are present and its inner matcher alone does not match.
3046 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003047 varDecl(hasInitializer(ignoringParenCasts(
3048 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003049 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003050 varDecl(hasInitializer(ignoringParenCasts(
3051 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003052
3053 // This test creates an implict cast from int to char in addition to the
3054 // parentheses.
3055 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003056 varDecl(hasInitializer(ignoringParenCasts(
3057 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003058
3059 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003060 varDecl(hasInitializer(ignoringParenCasts(
3061 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003062 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003063 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003064 integerLiteral(equals(0)))))));
3065}
3066
3067TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3068 // This test verifies that expressions that do not have any casts still match.
3069 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003070 varDecl(hasInitializer(ignoringParenCasts(
3071 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003072}
3073
3074TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3075 // These tests verify that ignoringImpCasts does not match if the inner
3076 // matcher does not match.
3077 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003078 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003079 unless(anything()))))));
3080
3081 // This test creates an implicit cast from int to char in addition to the
3082 // parentheses.
3083 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003084 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003085 unless(anything()))))));
3086
3087 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003088 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003089 unless(anything()))))));
3090}
3091
3092TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3093 // This test checks that ignoringParenAndImpCasts matches when
3094 // parentheses and/or implicit casts are present and its inner matcher alone
3095 // does not match.
3096 // Note that this test creates an implicit const cast.
3097 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003098 varDecl(hasInitializer(ignoringParenImpCasts(
3099 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003100 // This test creates an implicit cast from int to char.
3101 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003102 varDecl(hasInitializer(ignoringParenImpCasts(
3103 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003104}
3105
3106TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3107 // This test verifies that expressions that do not have parentheses or
3108 // implicit casts still match.
3109 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003110 varDecl(hasInitializer(ignoringParenImpCasts(
3111 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003112 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003113 varDecl(hasInitializer(ignoringParenImpCasts(
3114 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003115}
3116
3117TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3118 // These tests verify that ignoringParenImpCasts does not match if
3119 // the inner matcher does not match.
3120 // This test creates an implicit cast.
3121 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003122 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003123 unless(anything()))))));
3124 // These tests verify that ignoringParenAndImplictCasts does not look
3125 // through explicit casts.
3126 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003127 varDecl(hasInitializer(ignoringParenImpCasts(
3128 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003129 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003130 varDecl(hasInitializer(ignoringParenImpCasts(
3131 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003132 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003133 varDecl(hasInitializer(ignoringParenImpCasts(
3134 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003135}
3136
Manuel Klimeke9235692012-07-25 10:02:02 +00003137TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003138 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3139 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003140 implicitCastExpr(
3141 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003142}
3143
Manuel Klimeke9235692012-07-25 10:02:02 +00003144TEST(HasSourceExpression, MatchesExplicitCasts) {
3145 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003146 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003147 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003148 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003149}
3150
Manuel Klimek04616e42012-07-06 05:48:52 +00003151TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003152 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003153}
3154
3155TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003156 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003157}
3158
3159TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003160 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003161}
3162
3163TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003164 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003165}
3166
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003167TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3168 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3169 "const Foo f = Foo();",
3170 varDecl(hasInitializer(exprWithCleanups()))));
3171 EXPECT_FALSE(matches("struct Foo { };"
3172 "const Foo f = Foo();",
3173 varDecl(hasInitializer(exprWithCleanups()))));
3174}
3175
Daniel Jasper1dad1832012-07-10 20:20:19 +00003176TEST(InitListExpression, MatchesInitListExpression) {
3177 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3178 initListExpr(hasType(asString("int [2]")))));
3179 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003180 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003181 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3182 "void f();"
3183 "S s[1] = { &f };",
3184 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003185 EXPECT_TRUE(
3186 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003187}
3188
3189TEST(UsingDeclaration, MatchesUsingDeclarations) {
3190 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3191 usingDecl()));
3192}
3193
3194TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3195 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3196 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3197}
3198
3199TEST(UsingDeclaration, MatchesSpecificTarget) {
3200 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3201 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003202 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003203 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3204 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003205 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003206}
3207
3208TEST(UsingDeclaration, ThroughUsingDeclaration) {
3209 EXPECT_TRUE(matches(
3210 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003211 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003212 EXPECT_TRUE(notMatches(
3213 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003214 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003215}
3216
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003217TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3218 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3219 usingDirectiveDecl()));
3220 EXPECT_FALSE(
3221 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3222}
3223
Sam Panzerd624bfb2012-08-16 17:20:59 +00003224TEST(SingleDecl, IsSingleDecl) {
3225 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003226 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003227 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3228 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3229 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3230 SingleDeclStmt));
3231}
3232
3233TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003234 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003235
3236 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003237 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003238 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003239 declStmt(containsDeclaration(0, MatchesInit),
3240 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003241 unsigned WrongIndex = 42;
3242 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003243 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003244 MatchesInit))));
3245}
3246
3247TEST(DeclCount, DeclCountIsCorrect) {
3248 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003249 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003250 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003251 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003252 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003253 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003254}
3255
Manuel Klimek04616e42012-07-06 05:48:52 +00003256TEST(While, MatchesWhileLoops) {
3257 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3258 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3259 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3260}
3261
3262TEST(Do, MatchesDoLoops) {
3263 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3264 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3265}
3266
3267TEST(Do, DoesNotMatchWhileLoops) {
3268 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3269}
3270
3271TEST(SwitchCase, MatchesCase) {
3272 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3273 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3274 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3275 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3276}
3277
Daniel Jasper87c3d362012-09-20 14:12:57 +00003278TEST(SwitchCase, MatchesSwitch) {
3279 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3280 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3281 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3282 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3283}
3284
Peter Collingbourne3154a102013-05-10 11:52:02 +00003285TEST(SwitchCase, MatchesEachCase) {
3286 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3287 switchStmt(forEachSwitchCase(caseStmt()))));
3288 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3289 switchStmt(forEachSwitchCase(caseStmt()))));
3290 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3291 switchStmt(forEachSwitchCase(caseStmt()))));
3292 EXPECT_TRUE(notMatches(
3293 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3294 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3295 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3296 switchStmt(forEachSwitchCase(
3297 caseStmt(hasCaseConstant(integerLiteral()))))));
3298 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3299 switchStmt(forEachSwitchCase(
3300 caseStmt(hasCaseConstant(integerLiteral()))))));
3301 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3302 switchStmt(forEachSwitchCase(
3303 caseStmt(hasCaseConstant(integerLiteral()))))));
3304 EXPECT_TRUE(matchAndVerifyResultTrue(
3305 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3306 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3307 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3308}
3309
Manuel Klimekba46fc02013-07-19 11:50:54 +00003310TEST(ForEachConstructorInitializer, MatchesInitializers) {
3311 EXPECT_TRUE(matches(
3312 "struct X { X() : i(42), j(42) {} int i, j; };",
3313 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3314}
3315
Daniel Jasper87c3d362012-09-20 14:12:57 +00003316TEST(ExceptionHandling, SimpleCases) {
3317 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3318 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3319 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3320 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3321 throwExpr()));
3322 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3323 throwExpr()));
3324}
3325
Manuel Klimek04616e42012-07-06 05:48:52 +00003326TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3327 EXPECT_TRUE(notMatches(
3328 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003329 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003330 EXPECT_TRUE(notMatches(
3331 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003332 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003333}
3334
3335TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3336 EXPECT_TRUE(matches(
3337 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003338 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003339}
3340
3341TEST(ForEach, BindsOneNode) {
3342 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003343 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003344 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003345}
3346
3347TEST(ForEach, BindsMultipleNodes) {
3348 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003349 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003350 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003351}
3352
3353TEST(ForEach, BindsRecursiveCombinations) {
3354 EXPECT_TRUE(matchAndVerifyResultTrue(
3355 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003356 recordDecl(hasName("C"),
3357 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003358 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003359}
3360
3361TEST(ForEachDescendant, BindsOneNode) {
3362 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003363 recordDecl(hasName("C"),
3364 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003365 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003366}
3367
Daniel Jasper94a56852012-11-16 18:39:22 +00003368TEST(ForEachDescendant, NestedForEachDescendant) {
3369 DeclarationMatcher m = recordDecl(
3370 isDefinition(), decl().bind("x"), hasName("C"));
3371 EXPECT_TRUE(matchAndVerifyResultTrue(
3372 "class A { class B { class C {}; }; };",
3373 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3374 new VerifyIdIsBoundTo<Decl>("x", "C")));
3375
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003376 // Check that a partial match of 'm' that binds 'x' in the
3377 // first part of anyOf(m, anything()) will not overwrite the
3378 // binding created by the earlier binding in the hasDescendant.
3379 EXPECT_TRUE(matchAndVerifyResultTrue(
3380 "class A { class B { class C {}; }; };",
3381 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3382 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003383}
3384
Manuel Klimek04616e42012-07-06 05:48:52 +00003385TEST(ForEachDescendant, BindsMultipleNodes) {
3386 EXPECT_TRUE(matchAndVerifyResultTrue(
3387 "class C { class D { int x; int y; }; "
3388 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003389 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003390 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003391}
3392
3393TEST(ForEachDescendant, BindsRecursiveCombinations) {
3394 EXPECT_TRUE(matchAndVerifyResultTrue(
3395 "class C { class D { "
3396 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003397 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3398 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003399 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003400}
3401
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003402TEST(ForEachDescendant, BindsCombinations) {
3403 EXPECT_TRUE(matchAndVerifyResultTrue(
3404 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3405 "(true) {} }",
3406 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3407 forEachDescendant(whileStmt().bind("while"))),
3408 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3409}
3410
3411TEST(Has, DoesNotDeleteBindings) {
3412 EXPECT_TRUE(matchAndVerifyResultTrue(
3413 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3414 new VerifyIdIsBoundTo<Decl>("x", 1)));
3415}
3416
3417TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3418 // Those matchers cover all the cases where an inner matcher is called
3419 // and there is not a 1:1 relationship between the match of the outer
3420 // matcher and the match of the inner matcher.
3421 // The pattern to look for is:
3422 // ... return InnerMatcher.matches(...); ...
3423 // In which case no special handling is needed.
3424 //
3425 // On the other hand, if there are multiple alternative matches
3426 // (for example forEach*) or matches might be discarded (for example has*)
3427 // the implementation must make sure that the discarded matches do not
3428 // affect the bindings.
3429 // When new such matchers are added, add a test here that:
3430 // - matches a simple node, and binds it as the first thing in the matcher:
3431 // recordDecl(decl().bind("x"), hasName("X")))
3432 // - uses the matcher under test afterwards in a way that not the first
3433 // alternative is matched; for anyOf, that means the first branch
3434 // would need to return false; for hasAncestor, it means that not
3435 // the direct parent matches the inner matcher.
3436
3437 EXPECT_TRUE(matchAndVerifyResultTrue(
3438 "class X { int y; };",
3439 recordDecl(
3440 recordDecl().bind("x"), hasName("::X"),
3441 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3442 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3443 EXPECT_TRUE(matchAndVerifyResultTrue(
3444 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3445 anyOf(unless(anything()), anything())),
3446 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3447 EXPECT_TRUE(matchAndVerifyResultTrue(
3448 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3449 classTemplateSpecializationDecl(
3450 decl().bind("x"),
3451 hasAnyTemplateArgument(refersToType(asString("int")))),
3452 new VerifyIdIsBoundTo<Decl>("x", 1)));
3453 EXPECT_TRUE(matchAndVerifyResultTrue(
3454 "class X { void f(); void g(); };",
3455 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3456 new VerifyIdIsBoundTo<Decl>("x", 1)));
3457 EXPECT_TRUE(matchAndVerifyResultTrue(
3458 "class X { X() : a(1), b(2) {} double a; int b; };",
3459 recordDecl(decl().bind("x"),
3460 has(constructorDecl(
3461 hasAnyConstructorInitializer(forField(hasName("b")))))),
3462 new VerifyIdIsBoundTo<Decl>("x", 1)));
3463 EXPECT_TRUE(matchAndVerifyResultTrue(
3464 "void x(int, int) { x(0, 42); }",
3465 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3466 new VerifyIdIsBoundTo<Expr>("x", 1)));
3467 EXPECT_TRUE(matchAndVerifyResultTrue(
3468 "void x(int, int y) {}",
3469 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3470 new VerifyIdIsBoundTo<Decl>("x", 1)));
3471 EXPECT_TRUE(matchAndVerifyResultTrue(
3472 "void x() { return; if (true) {} }",
3473 functionDecl(decl().bind("x"),
3474 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3475 new VerifyIdIsBoundTo<Decl>("x", 1)));
3476 EXPECT_TRUE(matchAndVerifyResultTrue(
3477 "namespace X { void b(int); void b(); }"
3478 "using X::b;",
3479 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3480 functionDecl(parameterCountIs(1))))),
3481 new VerifyIdIsBoundTo<Decl>("x", 1)));
3482 EXPECT_TRUE(matchAndVerifyResultTrue(
3483 "class A{}; class B{}; class C : B, A {};",
3484 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3485 new VerifyIdIsBoundTo<Decl>("x", 1)));
3486 EXPECT_TRUE(matchAndVerifyResultTrue(
3487 "class A{}; typedef A B; typedef A C; typedef A D;"
3488 "class E : A {};",
3489 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3490 new VerifyIdIsBoundTo<Decl>("x", 1)));
3491 EXPECT_TRUE(matchAndVerifyResultTrue(
3492 "class A { class B { void f() {} }; };",
3493 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3494 new VerifyIdIsBoundTo<Decl>("x", 1)));
3495 EXPECT_TRUE(matchAndVerifyResultTrue(
3496 "template <typename T> struct A { struct B {"
3497 " void f() { if(true) {} }"
3498 "}; };"
3499 "void t() { A<int>::B b; b.f(); }",
3500 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3501 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3502 EXPECT_TRUE(matchAndVerifyResultTrue(
3503 "class A {};",
3504 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3505 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003506 EXPECT_TRUE(matchAndVerifyResultTrue(
3507 "class A { A() : s(), i(42) {} const char *s; int i; };",
3508 constructorDecl(hasName("::A::A"), decl().bind("x"),
3509 forEachConstructorInitializer(forField(hasName("i")))),
3510 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003511}
3512
Daniel Jasper33806cd2012-11-11 22:14:55 +00003513TEST(ForEachDescendant, BindsCorrectNodes) {
3514 EXPECT_TRUE(matchAndVerifyResultTrue(
3515 "class C { void f(); int i; };",
3516 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3517 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3518 EXPECT_TRUE(matchAndVerifyResultTrue(
3519 "class C { void f() {} int i; };",
3520 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3521 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3522}
3523
Manuel Klimekabf43712013-02-04 10:59:20 +00003524TEST(FindAll, BindsNodeOnMatch) {
3525 EXPECT_TRUE(matchAndVerifyResultTrue(
3526 "class A {};",
3527 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3528 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3529}
3530
3531TEST(FindAll, BindsDescendantNodeOnMatch) {
3532 EXPECT_TRUE(matchAndVerifyResultTrue(
3533 "class A { int a; int b; };",
3534 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3535 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3536}
3537
3538TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3539 EXPECT_TRUE(matchAndVerifyResultTrue(
3540 "class A { int a; int b; };",
3541 recordDecl(hasName("::A"),
3542 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3543 fieldDecl().bind("v"))))),
3544 new VerifyIdIsBoundTo<Decl>("v", 3)));
3545
3546 EXPECT_TRUE(matchAndVerifyResultTrue(
3547 "class A { class B {}; class C {}; };",
3548 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3549 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3550}
3551
Manuel Klimek88b95872013-02-04 09:42:38 +00003552TEST(EachOf, TriggersForEachMatch) {
3553 EXPECT_TRUE(matchAndVerifyResultTrue(
3554 "class A { int a; int b; };",
3555 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3556 has(fieldDecl(hasName("b")).bind("v")))),
3557 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3558}
3559
3560TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3561 EXPECT_TRUE(matchAndVerifyResultTrue(
3562 "class A { int a; int c; };",
3563 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3564 has(fieldDecl(hasName("b")).bind("v")))),
3565 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3566 EXPECT_TRUE(matchAndVerifyResultTrue(
3567 "class A { int c; int b; };",
3568 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3569 has(fieldDecl(hasName("b")).bind("v")))),
3570 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3571 EXPECT_TRUE(notMatches(
3572 "class A { int c; int d; };",
3573 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3574 has(fieldDecl(hasName("b")).bind("v"))))));
3575}
Manuel Klimek04616e42012-07-06 05:48:52 +00003576
3577TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3578 // Make sure that we can both match the class by name (::X) and by the type
3579 // the template was instantiated with (via a field).
3580
3581 EXPECT_TRUE(matches(
3582 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003583 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003584
3585 EXPECT_TRUE(matches(
3586 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003587 recordDecl(isTemplateInstantiation(), hasDescendant(
3588 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003589}
3590
3591TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3592 EXPECT_TRUE(matches(
3593 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003594 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003595 isTemplateInstantiation())));
3596}
3597
3598TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3599 EXPECT_TRUE(matches(
3600 "template <typename T> class X { T t; }; class A {};"
3601 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003602 recordDecl(isTemplateInstantiation(), hasDescendant(
3603 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003604}
3605
3606TEST(IsTemplateInstantiation,
3607 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3608 EXPECT_TRUE(matches(
3609 "template <typename T> class X {};"
3610 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003611 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003612}
3613
3614TEST(IsTemplateInstantiation,
3615 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3616 EXPECT_TRUE(matches(
3617 "class A {};"
3618 "class X {"
3619 " template <typename U> class Y { U u; };"
3620 " Y<A> y;"
3621 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003622 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003623}
3624
3625TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3626 // FIXME: Figure out whether this makes sense. It doesn't affect the
3627 // normal use case as long as the uppermost instantiation always is marked
3628 // as template instantiation, but it might be confusing as a predicate.
3629 EXPECT_TRUE(matches(
3630 "class A {};"
3631 "template <typename T> class X {"
3632 " template <typename U> class Y { U u; };"
3633 " Y<T> y;"
3634 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003635 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003636}
3637
3638TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3639 EXPECT_TRUE(notMatches(
3640 "template <typename T> class X {}; class A {};"
3641 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003642 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003643}
3644
3645TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3646 EXPECT_TRUE(notMatches(
3647 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003648 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003649}
3650
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003651TEST(IsInstantiated, MatchesInstantiation) {
3652 EXPECT_TRUE(
3653 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3654 recordDecl(isInstantiated())));
3655}
3656
3657TEST(IsInstantiated, NotMatchesDefinition) {
3658 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3659 recordDecl(isInstantiated())));
3660}
3661
3662TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3663 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3664 "class Y { A<int> a; }; Y y;",
3665 declStmt(isInTemplateInstantiation())));
3666}
3667
3668TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3669 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3670 declStmt(isInTemplateInstantiation())));
3671}
3672
3673TEST(IsInstantiated, MatchesFunctionInstantiation) {
3674 EXPECT_TRUE(
3675 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3676 functionDecl(isInstantiated())));
3677}
3678
3679TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3680 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3681 varDecl(isInstantiated())));
3682}
3683
3684TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3685 EXPECT_TRUE(
3686 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3687 declStmt(isInTemplateInstantiation())));
3688}
3689
3690TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3691 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3692 declStmt(isInTemplateInstantiation())));
3693}
3694
3695TEST(IsInTemplateInstantiation, Sharing) {
3696 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3697 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3698 // and makes the matcher behave in non-obvious ways.
3699 EXPECT_TRUE(notMatches(
3700 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3701 Matcher));
3702 EXPECT_TRUE(matches(
3703 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3704 Matcher));
3705}
3706
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003707TEST(IsExplicitTemplateSpecialization,
3708 DoesNotMatchPrimaryTemplate) {
3709 EXPECT_TRUE(notMatches(
3710 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003711 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003712 EXPECT_TRUE(notMatches(
3713 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003714 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003715}
3716
3717TEST(IsExplicitTemplateSpecialization,
3718 DoesNotMatchExplicitTemplateInstantiations) {
3719 EXPECT_TRUE(notMatches(
3720 "template <typename T> class X {};"
3721 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003722 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003723 EXPECT_TRUE(notMatches(
3724 "template <typename T> void f(T t) {}"
3725 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003726 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003727}
3728
3729TEST(IsExplicitTemplateSpecialization,
3730 DoesNotMatchImplicitTemplateInstantiations) {
3731 EXPECT_TRUE(notMatches(
3732 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003733 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003734 EXPECT_TRUE(notMatches(
3735 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003736 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003737}
3738
3739TEST(IsExplicitTemplateSpecialization,
3740 MatchesExplicitTemplateSpecializations) {
3741 EXPECT_TRUE(matches(
3742 "template <typename T> class X {};"
3743 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003744 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003745 EXPECT_TRUE(matches(
3746 "template <typename T> void f(T t) {}"
3747 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003748 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003749}
3750
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003751TEST(HasAncenstor, MatchesDeclarationAncestors) {
3752 EXPECT_TRUE(matches(
3753 "class A { class B { class C {}; }; };",
3754 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3755}
3756
3757TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3758 EXPECT_TRUE(notMatches(
3759 "class A { class B { class C {}; }; };",
3760 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3761}
3762
3763TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3764 EXPECT_TRUE(matches(
3765 "class A { class B { void f() { C c; } class C {}; }; };",
3766 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3767 hasAncestor(recordDecl(hasName("A"))))))));
3768}
3769
3770TEST(HasAncenstor, MatchesStatementAncestors) {
3771 EXPECT_TRUE(matches(
3772 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003773 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003774}
3775
3776TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3777 EXPECT_TRUE(matches(
3778 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003779 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003780}
3781
3782TEST(HasAncestor, BindsRecursiveCombinations) {
3783 EXPECT_TRUE(matchAndVerifyResultTrue(
3784 "class C { class D { class E { class F { int y; }; }; }; };",
3785 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003786 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003787}
3788
3789TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3790 EXPECT_TRUE(matchAndVerifyResultTrue(
3791 "class C { class D { class E { class F { int y; }; }; }; };",
3792 fieldDecl(hasAncestor(
3793 decl(
3794 hasDescendant(recordDecl(isDefinition(),
3795 hasAncestor(recordDecl())))
3796 ).bind("d")
3797 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003798 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003799}
3800
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003801TEST(HasAncestor, MatchesClosestAncestor) {
3802 EXPECT_TRUE(matchAndVerifyResultTrue(
3803 "template <typename T> struct C {"
3804 " void f(int) {"
3805 " struct I { void g(T) { int x; } } i; i.g(42);"
3806 " }"
3807 "};"
3808 "template struct C<int>;",
3809 varDecl(hasName("x"),
3810 hasAncestor(functionDecl(hasParameter(
3811 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3812 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3813}
3814
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003815TEST(HasAncestor, MatchesInTemplateInstantiations) {
3816 EXPECT_TRUE(matches(
3817 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3818 "A<int>::B::C a;",
3819 fieldDecl(hasType(asString("int")),
3820 hasAncestor(recordDecl(hasName("A"))))));
3821}
3822
3823TEST(HasAncestor, MatchesInImplicitCode) {
3824 EXPECT_TRUE(matches(
3825 "struct X {}; struct A { A() {} X x; };",
3826 constructorDecl(
3827 hasAnyConstructorInitializer(withInitializer(expr(
3828 hasAncestor(recordDecl(hasName("A")))))))));
3829}
3830
Daniel Jasper632aea92012-10-22 16:26:51 +00003831TEST(HasParent, MatchesOnlyParent) {
3832 EXPECT_TRUE(matches(
3833 "void f() { if (true) { int x = 42; } }",
3834 compoundStmt(hasParent(ifStmt()))));
3835 EXPECT_TRUE(notMatches(
3836 "void f() { for (;;) { int x = 42; } }",
3837 compoundStmt(hasParent(ifStmt()))));
3838 EXPECT_TRUE(notMatches(
3839 "void f() { if (true) for (;;) { int x = 42; } }",
3840 compoundStmt(hasParent(ifStmt()))));
3841}
3842
Manuel Klimekc844a462012-12-06 14:42:48 +00003843TEST(HasAncestor, MatchesAllAncestors) {
3844 EXPECT_TRUE(matches(
3845 "template <typename T> struct C { static void f() { 42; } };"
3846 "void t() { C<int>::f(); }",
3847 integerLiteral(
3848 equals(42),
3849 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3850 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3851}
3852
3853TEST(HasParent, MatchesAllParents) {
3854 EXPECT_TRUE(matches(
3855 "template <typename T> struct C { static void f() { 42; } };"
3856 "void t() { C<int>::f(); }",
3857 integerLiteral(
3858 equals(42),
3859 hasParent(compoundStmt(hasParent(functionDecl(
3860 hasParent(recordDecl(isTemplateInstantiation())))))))));
3861 EXPECT_TRUE(matches(
3862 "template <typename T> struct C { static void f() { 42; } };"
3863 "void t() { C<int>::f(); }",
3864 integerLiteral(
3865 equals(42),
3866 hasParent(compoundStmt(hasParent(functionDecl(
3867 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3868 EXPECT_TRUE(matches(
3869 "template <typename T> struct C { static void f() { 42; } };"
3870 "void t() { C<int>::f(); }",
3871 integerLiteral(equals(42),
3872 hasParent(compoundStmt(allOf(
3873 hasParent(functionDecl(
3874 hasParent(recordDecl(isTemplateInstantiation())))),
3875 hasParent(functionDecl(hasParent(recordDecl(
3876 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003877 EXPECT_TRUE(
3878 notMatches("template <typename T> struct C { static void f() {} };"
3879 "void t() { C<int>::f(); }",
3880 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003881}
3882
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003883TEST(HasParent, NoDuplicateParents) {
3884 class HasDuplicateParents : public BoundNodesCallback {
3885 public:
3886 bool run(const BoundNodes *Nodes) override { return false; }
3887 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3888 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3889 std::set<const void *> Parents;
3890 for (const auto &Parent : Context->getParents(*Node)) {
3891 if (!Parents.insert(Parent.getMemoizationData()).second) {
3892 return true;
3893 }
3894 }
3895 return false;
3896 }
3897 };
3898 EXPECT_FALSE(matchAndVerifyResultTrue(
3899 "template <typename T> int Foo() { return 1 + 2; }\n"
3900 "int x = Foo<int>() + Foo<unsigned>();",
3901 stmt().bind("node"), new HasDuplicateParents()));
3902}
3903
Daniel Jasper516b02e2012-10-17 08:52:59 +00003904TEST(TypeMatching, MatchesTypes) {
3905 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3906}
3907
Samuel Benzaquenb405c082014-12-15 15:09:22 +00003908TEST(TypeMatching, MatchesVoid) {
3909 EXPECT_TRUE(
3910 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
3911}
3912
Daniel Jasper516b02e2012-10-17 08:52:59 +00003913TEST(TypeMatching, MatchesArrayTypes) {
3914 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3915 EXPECT_TRUE(matches("int a[42];", arrayType()));
3916 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3917
3918 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3919 arrayType(hasElementType(builtinType()))));
3920
3921 EXPECT_TRUE(matches(
3922 "int const a[] = { 2, 3 };",
3923 qualType(arrayType(hasElementType(builtinType())))));
3924 EXPECT_TRUE(matches(
3925 "int const a[] = { 2, 3 };",
3926 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3927 EXPECT_TRUE(matches(
3928 "typedef const int T; T x[] = { 1, 2 };",
3929 qualType(isConstQualified(), arrayType())));
3930
3931 EXPECT_TRUE(notMatches(
3932 "int a[] = { 2, 3 };",
3933 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3934 EXPECT_TRUE(notMatches(
3935 "int a[] = { 2, 3 };",
3936 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3937 EXPECT_TRUE(notMatches(
3938 "int const a[] = { 2, 3 };",
3939 qualType(arrayType(hasElementType(builtinType())),
3940 unless(isConstQualified()))));
3941
3942 EXPECT_TRUE(matches("int a[2];",
3943 constantArrayType(hasElementType(builtinType()))));
3944 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3945}
3946
3947TEST(TypeMatching, MatchesComplexTypes) {
3948 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3949 EXPECT_TRUE(matches(
3950 "_Complex float f;",
3951 complexType(hasElementType(builtinType()))));
3952 EXPECT_TRUE(notMatches(
3953 "_Complex float f;",
3954 complexType(hasElementType(isInteger()))));
3955}
3956
3957TEST(TypeMatching, MatchesConstantArrayTypes) {
3958 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3959 EXPECT_TRUE(notMatches(
3960 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3961 constantArrayType(hasElementType(builtinType()))));
3962
3963 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3964 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3965 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3966}
3967
3968TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3969 EXPECT_TRUE(matches(
3970 "template <typename T, int Size> class array { T data[Size]; };",
3971 dependentSizedArrayType()));
3972 EXPECT_TRUE(notMatches(
3973 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3974 dependentSizedArrayType()));
3975}
3976
3977TEST(TypeMatching, MatchesIncompleteArrayType) {
3978 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3979 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3980
3981 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3982 incompleteArrayType()));
3983}
3984
3985TEST(TypeMatching, MatchesVariableArrayType) {
3986 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3987 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3988
3989 EXPECT_TRUE(matches(
3990 "void f(int b) { int a[b]; }",
3991 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3992 varDecl(hasName("b")))))))));
3993}
3994
3995TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003996 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3997 llvm::Triple::Win32) {
3998 // FIXME: Make this work for MSVC.
3999 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004000
David Majnemer197e2102014-03-05 06:32:38 +00004001 EXPECT_TRUE(matches("_Atomic(int) i;",
4002 atomicType(hasValueType(isInteger()))));
4003 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4004 atomicType(hasValueType(isInteger()))));
4005 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004006}
4007
4008TEST(TypeMatching, MatchesAutoTypes) {
4009 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4010 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4011 autoType()));
4012
Richard Smith061f1e22013-04-30 21:23:01 +00004013 // FIXME: Matching against the type-as-written can't work here, because the
4014 // type as written was not deduced.
4015 //EXPECT_TRUE(matches("auto a = 1;",
4016 // autoType(hasDeducedType(isInteger()))));
4017 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4018 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004019}
4020
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004021TEST(TypeMatching, MatchesFunctionTypes) {
4022 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4023 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4024}
4025
Edwin Vaneec074802013-04-01 18:33:34 +00004026TEST(TypeMatching, MatchesParenType) {
4027 EXPECT_TRUE(
4028 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4029 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4030
4031 EXPECT_TRUE(matches(
4032 "int (*ptr_to_func)(int);",
4033 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4034 EXPECT_TRUE(notMatches(
4035 "int (*ptr_to_array)[4];",
4036 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4037}
4038
Daniel Jasper516b02e2012-10-17 08:52:59 +00004039TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004040 // FIXME: Reactive when these tests can be more specific (not matching
4041 // implicit code on certain platforms), likely when we have hasDescendant for
4042 // Types/TypeLocs.
4043 //EXPECT_TRUE(matchAndVerifyResultTrue(
4044 // "int* a;",
4045 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4046 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4047 //EXPECT_TRUE(matchAndVerifyResultTrue(
4048 // "int* a;",
4049 // pointerTypeLoc().bind("loc"),
4050 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004051 EXPECT_TRUE(matches(
4052 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004053 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004054 EXPECT_TRUE(matches(
4055 "int** a;",
4056 loc(pointerType(pointee(pointerType())))));
4057 EXPECT_TRUE(matches(
4058 "int* b; int* * const a = &b;",
4059 loc(qualType(isConstQualified(), pointerType()))));
4060
4061 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004062 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4063 hasType(blockPointerType()))));
4064 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4065 hasType(memberPointerType()))));
4066 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4067 hasType(pointerType()))));
4068 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4069 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004070 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4071 hasType(lValueReferenceType()))));
4072 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4073 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004074
Daniel Jasper7943eb52012-10-17 13:35:36 +00004075 Fragment = "int *ptr;";
4076 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4077 hasType(blockPointerType()))));
4078 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4079 hasType(memberPointerType()))));
4080 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4081 hasType(pointerType()))));
4082 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4083 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004084
Daniel Jasper7943eb52012-10-17 13:35:36 +00004085 Fragment = "int a; int &ref = a;";
4086 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4087 hasType(blockPointerType()))));
4088 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4089 hasType(memberPointerType()))));
4090 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4091 hasType(pointerType()))));
4092 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4093 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004094 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4095 hasType(lValueReferenceType()))));
4096 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4097 hasType(rValueReferenceType()))));
4098
4099 Fragment = "int &&ref = 2;";
4100 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4101 hasType(blockPointerType()))));
4102 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4103 hasType(memberPointerType()))));
4104 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4105 hasType(pointerType()))));
4106 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4107 hasType(referenceType()))));
4108 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4109 hasType(lValueReferenceType()))));
4110 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4111 hasType(rValueReferenceType()))));
4112}
4113
4114TEST(TypeMatching, AutoRefTypes) {
4115 std::string Fragment = "auto a = 1;"
4116 "auto b = a;"
4117 "auto &c = a;"
4118 "auto &&d = c;"
4119 "auto &&e = 2;";
4120 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4121 hasType(referenceType()))));
4122 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4123 hasType(referenceType()))));
4124 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4125 hasType(referenceType()))));
4126 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4127 hasType(lValueReferenceType()))));
4128 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4129 hasType(rValueReferenceType()))));
4130 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4131 hasType(referenceType()))));
4132 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4133 hasType(lValueReferenceType()))));
4134 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4135 hasType(rValueReferenceType()))));
4136 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4137 hasType(referenceType()))));
4138 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4139 hasType(lValueReferenceType()))));
4140 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4141 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004142}
4143
4144TEST(TypeMatching, PointeeTypes) {
4145 EXPECT_TRUE(matches("int b; int &a = b;",
4146 referenceType(pointee(builtinType()))));
4147 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4148
4149 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004150 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004151
4152 EXPECT_TRUE(matches(
4153 "int const *A;",
4154 pointerType(pointee(isConstQualified(), builtinType()))));
4155 EXPECT_TRUE(notMatches(
4156 "int *A;",
4157 pointerType(pointee(isConstQualified(), builtinType()))));
4158}
4159
4160TEST(TypeMatching, MatchesPointersToConstTypes) {
4161 EXPECT_TRUE(matches("int b; int * const a = &b;",
4162 loc(pointerType())));
4163 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004164 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004165 EXPECT_TRUE(matches(
4166 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004167 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004168 EXPECT_TRUE(matches(
4169 "int b; const int * a = &b;",
4170 pointerType(pointee(builtinType()))));
4171}
4172
4173TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004174 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4175 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004176}
4177
Edwin Vanef901b712013-02-25 14:49:29 +00004178TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004179 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004180 templateSpecializationType()));
4181}
4182
Edwin Vaneb6eae142013-02-25 20:43:32 +00004183TEST(TypeMatching, MatchesRecordType) {
4184 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004185 EXPECT_TRUE(matches("struct S{}; S s;",
4186 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4187 EXPECT_TRUE(notMatches("int i;",
4188 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004189}
4190
4191TEST(TypeMatching, MatchesElaboratedType) {
4192 EXPECT_TRUE(matches(
4193 "namespace N {"
4194 " namespace M {"
4195 " class D {};"
4196 " }"
4197 "}"
4198 "N::M::D d;", elaboratedType()));
4199 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4200 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4201}
4202
4203TEST(ElaboratedTypeNarrowing, hasQualifier) {
4204 EXPECT_TRUE(matches(
4205 "namespace N {"
4206 " namespace M {"
4207 " class D {};"
4208 " }"
4209 "}"
4210 "N::M::D d;",
4211 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4212 EXPECT_TRUE(notMatches(
4213 "namespace M {"
4214 " class D {};"
4215 "}"
4216 "M::D d;",
4217 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004218 EXPECT_TRUE(notMatches(
4219 "struct D {"
4220 "} d;",
4221 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004222}
4223
4224TEST(ElaboratedTypeNarrowing, namesType) {
4225 EXPECT_TRUE(matches(
4226 "namespace N {"
4227 " namespace M {"
4228 " class D {};"
4229 " }"
4230 "}"
4231 "N::M::D d;",
4232 elaboratedType(elaboratedType(namesType(recordType(
4233 hasDeclaration(namedDecl(hasName("D")))))))));
4234 EXPECT_TRUE(notMatches(
4235 "namespace M {"
4236 " class D {};"
4237 "}"
4238 "M::D d;",
4239 elaboratedType(elaboratedType(namesType(typedefType())))));
4240}
4241
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004242TEST(NNS, MatchesNestedNameSpecifiers) {
4243 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4244 nestedNameSpecifier()));
4245 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4246 nestedNameSpecifier()));
4247 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4248 nestedNameSpecifier()));
4249
4250 EXPECT_TRUE(matches(
4251 "struct A { static void f() {} }; void g() { A::f(); }",
4252 nestedNameSpecifier()));
4253 EXPECT_TRUE(notMatches(
4254 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4255 nestedNameSpecifier()));
4256}
4257
Daniel Jasper87c3d362012-09-20 14:12:57 +00004258TEST(NullStatement, SimpleCases) {
4259 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4260 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4261}
4262
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004263TEST(NNS, MatchesTypes) {
4264 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4265 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4266 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4267 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4268 Matcher));
4269 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4270}
4271
4272TEST(NNS, MatchesNamespaceDecls) {
4273 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4274 specifiesNamespace(hasName("ns")));
4275 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4276 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4277 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4278}
4279
4280TEST(NNS, BindsNestedNameSpecifiers) {
4281 EXPECT_TRUE(matchAndVerifyResultTrue(
4282 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4283 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4284 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4285}
4286
4287TEST(NNS, BindsNestedNameSpecifierLocs) {
4288 EXPECT_TRUE(matchAndVerifyResultTrue(
4289 "namespace ns { struct B {}; } ns::B b;",
4290 loc(nestedNameSpecifier()).bind("loc"),
4291 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4292}
4293
4294TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4295 EXPECT_TRUE(matches(
4296 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4297 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4298 EXPECT_TRUE(matches(
4299 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004300 nestedNameSpecifierLoc(hasPrefix(
4301 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004302}
4303
Daniel Jasper6fc34332012-10-30 15:42:00 +00004304TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4305 std::string Fragment =
4306 "namespace a { struct A { struct B { struct C {}; }; }; };"
4307 "void f() { a::A::B::C c; }";
4308 EXPECT_TRUE(matches(
4309 Fragment,
4310 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4311 hasDescendant(nestedNameSpecifier(
4312 specifiesNamespace(hasName("a")))))));
4313 EXPECT_TRUE(notMatches(
4314 Fragment,
4315 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4316 has(nestedNameSpecifier(
4317 specifiesNamespace(hasName("a")))))));
4318 EXPECT_TRUE(matches(
4319 Fragment,
4320 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4321 has(nestedNameSpecifier(
4322 specifiesNamespace(hasName("a")))))));
4323
4324 // Not really useful because a NestedNameSpecifier can af at most one child,
4325 // but to complete the interface.
4326 EXPECT_TRUE(matchAndVerifyResultTrue(
4327 Fragment,
4328 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4329 forEach(nestedNameSpecifier().bind("x"))),
4330 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4331}
4332
4333TEST(NNS, NestedNameSpecifiersAsDescendants) {
4334 std::string Fragment =
4335 "namespace a { struct A { struct B { struct C {}; }; }; };"
4336 "void f() { a::A::B::C c; }";
4337 EXPECT_TRUE(matches(
4338 Fragment,
4339 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4340 asString("struct a::A")))))));
4341 EXPECT_TRUE(matchAndVerifyResultTrue(
4342 Fragment,
4343 functionDecl(hasName("f"),
4344 forEachDescendant(nestedNameSpecifier().bind("x"))),
4345 // Nested names: a, a::A and a::A::B.
4346 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4347}
4348
4349TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4350 std::string Fragment =
4351 "namespace a { struct A { struct B { struct C {}; }; }; };"
4352 "void f() { a::A::B::C c; }";
4353 EXPECT_TRUE(matches(
4354 Fragment,
4355 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4356 hasDescendant(loc(nestedNameSpecifier(
4357 specifiesNamespace(hasName("a"))))))));
4358 EXPECT_TRUE(notMatches(
4359 Fragment,
4360 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4361 has(loc(nestedNameSpecifier(
4362 specifiesNamespace(hasName("a"))))))));
4363 EXPECT_TRUE(matches(
4364 Fragment,
4365 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4366 has(loc(nestedNameSpecifier(
4367 specifiesNamespace(hasName("a"))))))));
4368
4369 EXPECT_TRUE(matchAndVerifyResultTrue(
4370 Fragment,
4371 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4372 forEach(nestedNameSpecifierLoc().bind("x"))),
4373 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4374}
4375
4376TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4377 std::string Fragment =
4378 "namespace a { struct A { struct B { struct C {}; }; }; };"
4379 "void f() { a::A::B::C c; }";
4380 EXPECT_TRUE(matches(
4381 Fragment,
4382 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4383 asString("struct a::A"))))))));
4384 EXPECT_TRUE(matchAndVerifyResultTrue(
4385 Fragment,
4386 functionDecl(hasName("f"),
4387 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4388 // Nested names: a, a::A and a::A::B.
4389 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4390}
4391
Manuel Klimek191c0932013-02-01 13:41:35 +00004392template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004393public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004394 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4395 StringRef InnerId)
4396 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004397 }
4398
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004399 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004400
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004401 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004402 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004403 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4404 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004405 }
4406private:
4407 std::string Id;
4408 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004409 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004410};
4411
4412TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004413 EXPECT_TRUE(matchAndVerifyResultTrue(
4414 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4415 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004416 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4417 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004418 EXPECT_TRUE(matchAndVerifyResultFalse(
4419 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4420 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004421 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4422 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004423}
4424
4425TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004426 EXPECT_TRUE(matchAndVerifyResultTrue(
4427 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004428 new VerifyMatchOnNode<clang::Stmt>(
4429 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004430 EXPECT_TRUE(matchAndVerifyResultFalse(
4431 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004432 new VerifyMatchOnNode<clang::Stmt>(
4433 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004434}
4435
4436TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4437 EXPECT_TRUE(matchAndVerifyResultTrue(
4438 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4439 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004440 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004441 EXPECT_TRUE(matchAndVerifyResultFalse(
4442 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4443 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004444 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004445}
4446
Manuel Klimekbee08572013-02-07 12:42:10 +00004447template <typename T>
4448class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4449public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004450 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004451
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004452 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004453 const T *Node = Nodes->getNodeAs<T>("");
4454 return verify(*Nodes, *Context, Node);
4455 }
4456
4457 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004458 // Use the original typed pointer to verify we can pass pointers to subtypes
4459 // to equalsNode.
4460 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004461 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004462 "", match(stmt(hasParent(
4463 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004464 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004465 }
4466 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004467 // Use the original typed pointer to verify we can pass pointers to subtypes
4468 // to equalsNode.
4469 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004470 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004471 "", match(decl(hasParent(
4472 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004473 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004474 }
4475};
4476
4477TEST(IsEqualTo, MatchesNodesByIdentity) {
4478 EXPECT_TRUE(matchAndVerifyResultTrue(
4479 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004480 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4481 EXPECT_TRUE(matchAndVerifyResultTrue(
4482 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4483 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004484}
4485
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004486TEST(MatchFinder, CheckProfiling) {
4487 MatchFinder::MatchFinderOptions Options;
4488 llvm::StringMap<llvm::TimeRecord> Records;
4489 Options.CheckProfiling.emplace(Records);
4490 MatchFinder Finder(std::move(Options));
4491
4492 struct NamedCallback : public MatchFinder::MatchCallback {
4493 void run(const MatchFinder::MatchResult &Result) override {}
4494 StringRef getID() const override { return "MyID"; }
4495 } Callback;
4496 Finder.addMatcher(decl(), &Callback);
4497 std::unique_ptr<FrontendActionFactory> Factory(
4498 newFrontendActionFactory(&Finder));
4499 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4500
4501 EXPECT_EQ(1u, Records.size());
4502 EXPECT_EQ("MyID", Records.begin()->getKey());
4503}
4504
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004505class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4506public:
4507 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004508 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004509 EXPECT_TRUE(Called);
4510 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004511 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004512 bool Called;
4513};
4514
4515TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4516 MatchFinder Finder;
4517 VerifyStartOfTranslationUnit VerifyCallback;
4518 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004519 std::unique_ptr<FrontendActionFactory> Factory(
4520 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004521 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4522 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004523
4524 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004525 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004526 ASSERT_TRUE(AST.get());
4527 Finder.matchAST(AST->getASTContext());
4528 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004529}
4530
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004531class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4532public:
4533 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004534 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004535 EXPECT_FALSE(Called);
4536 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004537 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004538 bool Called;
4539};
4540
4541TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4542 MatchFinder Finder;
4543 VerifyEndOfTranslationUnit VerifyCallback;
4544 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004545 std::unique_ptr<FrontendActionFactory> Factory(
4546 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004547 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4548 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004549
4550 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004551 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004552 ASSERT_TRUE(AST.get());
4553 Finder.matchAST(AST->getASTContext());
4554 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004555}
4556
Manuel Klimekbbb75852013-06-20 14:06:32 +00004557TEST(EqualsBoundNodeMatcher, QualType) {
4558 EXPECT_TRUE(matches(
4559 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4560 hasInitializer(ignoringParenImpCasts(
4561 hasType(qualType(equalsBoundNode("type"))))))));
4562 EXPECT_TRUE(notMatches("int i = 1.f;",
4563 varDecl(hasType(qualType().bind("type")),
4564 hasInitializer(ignoringParenImpCasts(hasType(
4565 qualType(equalsBoundNode("type"))))))));
4566}
4567
4568TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4569 EXPECT_TRUE(notMatches(
4570 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4571 hasInitializer(ignoringParenImpCasts(
4572 hasType(qualType(equalsBoundNode("type"))))))));
4573}
4574
4575TEST(EqualsBoundNodeMatcher, Stmt) {
4576 EXPECT_TRUE(
4577 matches("void f() { if(true) {} }",
4578 stmt(allOf(ifStmt().bind("if"),
4579 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4580
4581 EXPECT_TRUE(notMatches(
4582 "void f() { if(true) { if (true) {} } }",
4583 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4584}
4585
4586TEST(EqualsBoundNodeMatcher, Decl) {
4587 EXPECT_TRUE(matches(
4588 "class X { class Y {}; };",
4589 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4590 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4591
4592 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4593 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4594 has(decl(equalsBoundNode("record")))))));
4595}
4596
4597TEST(EqualsBoundNodeMatcher, Type) {
4598 EXPECT_TRUE(matches(
4599 "class X { int a; int b; };",
4600 recordDecl(
4601 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4602 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4603
4604 EXPECT_TRUE(notMatches(
4605 "class X { int a; double b; };",
4606 recordDecl(
4607 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4608 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4609}
4610
4611TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004612 EXPECT_TRUE(matchAndVerifyResultTrue(
4613 "int f() {"
4614 " if (1) {"
4615 " int i = 9;"
4616 " }"
4617 " int j = 10;"
4618 " {"
4619 " float k = 9.0;"
4620 " }"
4621 " return 0;"
4622 "}",
4623 // Look for variable declarations within functions whose type is the same
4624 // as the function return type.
4625 functionDecl(returns(qualType().bind("type")),
4626 forEachDescendant(varDecl(hasType(
4627 qualType(equalsBoundNode("type")))).bind("decl"))),
4628 // Only i and j should match, not k.
4629 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4630}
4631
4632TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4633 EXPECT_TRUE(matchAndVerifyResultTrue(
4634 "void f() {"
4635 " int x;"
4636 " double d;"
4637 " x = d + x - d + x;"
4638 "}",
4639 functionDecl(
4640 hasName("f"), forEachDescendant(varDecl().bind("d")),
4641 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4642 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4643}
4644
Manuel Klimekce68f772014-03-25 14:39:26 +00004645TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4646 EXPECT_TRUE(matchAndVerifyResultTrue(
4647 "struct StringRef { int size() const; const char* data() const; };"
4648 "void f(StringRef v) {"
4649 " v.data();"
4650 "}",
4651 memberCallExpr(
4652 callee(methodDecl(hasName("data"))),
4653 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4654 .bind("var")))),
4655 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4656 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4657 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4658 .bind("data"),
4659 new VerifyIdIsBoundTo<Expr>("data", 1)));
4660
4661 EXPECT_FALSE(matches(
4662 "struct StringRef { int size() const; const char* data() const; };"
4663 "void f(StringRef v) {"
4664 " v.data();"
4665 " v.size();"
4666 "}",
4667 memberCallExpr(
4668 callee(methodDecl(hasName("data"))),
4669 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4670 .bind("var")))),
4671 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4672 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4673 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4674 .bind("data")));
4675}
4676
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004677TEST(TypeDefDeclMatcher, Match) {
4678 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4679 typedefDecl(hasName("typedefDeclTest"))));
4680}
4681
4682// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4683#ifndef LLVM_ON_WIN32
4684
4685TEST(Matcher, IsExpansionInMainFileMatcher) {
4686 EXPECT_TRUE(matches("class X {};",
4687 recordDecl(hasName("X"), isExpansionInMainFile())));
4688 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4689 FileContentMappings M;
4690 M.push_back(std::make_pair("/other", "class X {};"));
4691 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4692 recordDecl(isExpansionInMainFile()), false,
4693 "-isystem/", M));
4694}
4695
4696TEST(Matcher, IsExpansionInSystemHeader) {
4697 FileContentMappings M;
4698 M.push_back(std::make_pair("/other", "class X {};"));
4699 EXPECT_TRUE(matchesConditionally(
4700 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4701 "-isystem/", M));
4702 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4703 recordDecl(isExpansionInSystemHeader()),
4704 false, "-I/", M));
4705 EXPECT_TRUE(notMatches("class X {};",
4706 recordDecl(isExpansionInSystemHeader())));
4707 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4708}
4709
4710TEST(Matcher, IsExpansionInFileMatching) {
4711 FileContentMappings M;
4712 M.push_back(std::make_pair("/foo", "class A {};"));
4713 M.push_back(std::make_pair("/bar", "class B {};"));
4714 EXPECT_TRUE(matchesConditionally(
4715 "#include <foo>\n"
4716 "#include <bar>\n"
4717 "class X {};",
4718 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4719 "-isystem/", M));
4720 EXPECT_TRUE(matchesConditionally(
4721 "#include <foo>\n"
4722 "#include <bar>\n"
4723 "class X {};",
4724 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4725 "-isystem/", M));
4726}
4727
4728#endif // LLVM_ON_WIN32
4729
Manuel Klimekbfa43572015-03-12 15:48:15 +00004730
4731TEST(ObjCMessageExprMatcher, SimpleExprs) {
4732 // don't find ObjCMessageExpr where none are present
4733 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
4734
4735 std::string Objc1String =
4736 "@interface Str "
4737 " - (Str *)uppercaseString:(Str *)str;"
4738 "@end "
4739 "@interface foo "
4740 "- (void)meth:(Str *)text;"
4741 "@end "
4742 " "
4743 "@implementation foo "
4744 "- (void) meth:(Str *)text { "
4745 " [self contents];"
4746 " Str *up = [text uppercaseString];"
4747 "} "
4748 "@end ";
4749 EXPECT_TRUE(matchesObjC(
4750 Objc1String,
4751 objcMessageExpr(anything())));
4752 EXPECT_TRUE(matchesObjC(
4753 Objc1String,
4754 objcMessageExpr(hasSelector("contents"))));
4755 EXPECT_TRUE(matchesObjC(
4756 Objc1String,
4757 objcMessageExpr(matchesSelector("cont*"))));
4758 EXPECT_FALSE(matchesObjC(
4759 Objc1String,
4760 objcMessageExpr(matchesSelector("?cont*"))));
4761 EXPECT_TRUE(notMatchesObjC(
4762 Objc1String,
4763 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
4764 EXPECT_TRUE(matchesObjC(
4765 Objc1String,
4766 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
4767 EXPECT_TRUE(matchesObjC(
4768 Objc1String,
4769 objcMessageExpr(matchesSelector("uppercase*"),
4770 argumentCountIs(0)
4771 )));
4772
4773}
4774
Manuel Klimek04616e42012-07-06 05:48:52 +00004775} // end namespace ast_matchers
4776} // end namespace clang