blob: 46ddb8d0fb66ffe3c82a20ac4d1e524ed8e5d724 [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
Manuel Klimek04616e42012-07-06 05:48:52 +00001598TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1599 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001600 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001601}
1602
1603TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1604 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001605 methodDecl(hasAnyParameter(hasType(pointsTo(
1606 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001607}
1608
Alp Toker8db6e7a2014-01-05 06:38:57 +00001609TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001610 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001611 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001612 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001613 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001614}
1615
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001616TEST(Matcher, MatchesClassTemplateSpecialization) {
1617 EXPECT_TRUE(matches("template<typename T> struct A {};"
1618 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001619 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001620 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001621 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001622 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001623 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001624}
1625
Manuel Klimekc16c6522013-06-20 13:08:29 +00001626TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1627 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1628 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1629}
1630
1631TEST(ParmVarDecl, MatchesParmVars) {
1632 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1633 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1634}
1635
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001636TEST(Matcher, MatchesTypeTemplateArgument) {
1637 EXPECT_TRUE(matches(
1638 "template<typename T> struct B {};"
1639 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001640 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001641 asString("int"))))));
1642}
1643
1644TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1645 EXPECT_TRUE(matches(
1646 "struct B { int next; };"
1647 "template<int(B::*next_ptr)> struct A {};"
1648 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001649 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1650 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001651
1652 EXPECT_TRUE(notMatches(
1653 "template <typename T> struct A {};"
1654 "A<int> a;",
1655 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1656 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001657
1658 EXPECT_TRUE(matches(
1659 "struct B { int next; };"
1660 "template<int(B::*next_ptr)> struct A {};"
1661 "A<&B::next> a;",
1662 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1663 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1664
1665 EXPECT_TRUE(notMatches(
1666 "template <typename T> struct A {};"
1667 "A<int> a;",
1668 templateSpecializationType(hasAnyTemplateArgument(
1669 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001670}
1671
1672TEST(Matcher, MatchesSpecificArgument) {
1673 EXPECT_TRUE(matches(
1674 "template<typename T, typename U> class A {};"
1675 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001676 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001677 1, refersToType(asString("int"))))));
1678 EXPECT_TRUE(notMatches(
1679 "template<typename T, typename U> class A {};"
1680 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001681 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001682 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001683
1684 EXPECT_TRUE(matches(
1685 "template<typename T, typename U> class A {};"
1686 "A<bool, int> a;",
1687 templateSpecializationType(hasTemplateArgument(
1688 1, refersToType(asString("int"))))));
1689 EXPECT_TRUE(notMatches(
1690 "template<typename T, typename U> class A {};"
1691 "A<int, bool> a;",
1692 templateSpecializationType(hasTemplateArgument(
1693 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001694}
1695
Manuel Klimek7735e402014-10-09 13:06:22 +00001696TEST(TemplateArgument, Matches) {
1697 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1698 classTemplateSpecializationDecl(
1699 hasAnyTemplateArgument(templateArgument()))));
1700 EXPECT_TRUE(matches(
1701 "template<typename T> struct C {}; C<int> c;",
1702 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1703}
1704
1705TEST(TemplateArgumentCountIs, Matches) {
1706 EXPECT_TRUE(
1707 matches("template<typename T> struct C {}; C<int> c;",
1708 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1709 EXPECT_TRUE(
1710 notMatches("template<typename T> struct C {}; C<int> c;",
1711 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1712
1713 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1714 templateSpecializationType(templateArgumentCountIs(1))));
1715 EXPECT_TRUE(
1716 notMatches("template<typename T> struct C {}; C<int> c;",
1717 templateSpecializationType(templateArgumentCountIs(2))));
1718}
1719
1720TEST(IsIntegral, Matches) {
1721 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1722 classTemplateSpecializationDecl(
1723 hasAnyTemplateArgument(isIntegral()))));
1724 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1725 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1726 templateArgument(isIntegral())))));
1727}
1728
1729TEST(RefersToIntegralType, Matches) {
1730 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1731 classTemplateSpecializationDecl(
1732 hasAnyTemplateArgument(refersToIntegralType(
1733 asString("int"))))));
1734 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1735 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1736 refersToIntegralType(asString("int"))))));
1737}
1738
1739TEST(EqualsIntegralValue, Matches) {
1740 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1741 classTemplateSpecializationDecl(
1742 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1743 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1744 classTemplateSpecializationDecl(
1745 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1746 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1747 classTemplateSpecializationDecl(
1748 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1749 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1750 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1751 equalsIntegralValue("0042")))));
1752}
1753
Daniel Jasper639522c2013-02-25 12:02:08 +00001754TEST(Matcher, MatchesAccessSpecDecls) {
1755 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1756 EXPECT_TRUE(
1757 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1758 EXPECT_TRUE(
1759 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1760 EXPECT_TRUE(
1761 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1762
1763 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1764}
1765
Edwin Vane37ee1d72013-04-09 20:46:36 +00001766TEST(Matcher, MatchesVirtualMethod) {
1767 EXPECT_TRUE(matches("class X { virtual int f(); };",
1768 methodDecl(isVirtual(), hasName("::X::f"))));
1769 EXPECT_TRUE(notMatches("class X { int f(); };",
1770 methodDecl(isVirtual())));
1771}
1772
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001773TEST(Matcher, MatchesPureMethod) {
1774 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1775 methodDecl(isPure(), hasName("::X::f"))));
1776 EXPECT_TRUE(notMatches("class X { int f(); };",
1777 methodDecl(isPure())));
1778}
1779
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001780TEST(Matcher, MatchesConstMethod) {
1781 EXPECT_TRUE(matches("struct A { void foo() const; };",
1782 methodDecl(isConst())));
1783 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1784 methodDecl(isConst())));
1785}
1786
Edwin Vane37ee1d72013-04-09 20:46:36 +00001787TEST(Matcher, MatchesOverridingMethod) {
1788 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1789 "class Y : public X { int f(); };",
1790 methodDecl(isOverride(), hasName("::Y::f"))));
1791 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1792 "class Y : public X { int f(); };",
1793 methodDecl(isOverride(), hasName("::X::f"))));
1794 EXPECT_TRUE(notMatches("class X { int f(); }; "
1795 "class Y : public X { int f(); };",
1796 methodDecl(isOverride())));
1797 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1798 methodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001799 EXPECT_TRUE(
1800 matches("template <typename Base> struct Y : Base { void f() override;};",
1801 methodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001802}
1803
Manuel Klimek04616e42012-07-06 05:48:52 +00001804TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001805 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001806
1807 EXPECT_TRUE(
1808 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1809 EXPECT_TRUE(
1810 matches("class X { public: X(); }; void x() { X x = X(); }",
1811 Constructor));
1812 EXPECT_TRUE(
1813 matches("class X { public: X(int); }; void x() { X x = 0; }",
1814 Constructor));
1815 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1816}
1817
1818TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001819 StatementMatcher Constructor = constructExpr(
1820 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001821
1822 EXPECT_TRUE(
1823 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1824 Constructor));
1825 EXPECT_TRUE(
1826 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1827 Constructor));
1828 EXPECT_TRUE(
1829 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1830 Constructor));
1831 EXPECT_TRUE(
1832 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1833 Constructor));
1834
Daniel Jasper848cbe12012-09-18 13:09:13 +00001835 StatementMatcher WrongIndex = constructExpr(
1836 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001837 EXPECT_TRUE(
1838 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1839 WrongIndex));
1840}
1841
1842TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001843 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001844
1845 EXPECT_TRUE(
1846 matches("class X { public: X(int); }; void x() { X x(0); }",
1847 Constructor1Arg));
1848 EXPECT_TRUE(
1849 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1850 Constructor1Arg));
1851 EXPECT_TRUE(
1852 matches("class X { public: X(int); }; void x() { X x = 0; }",
1853 Constructor1Arg));
1854 EXPECT_TRUE(
1855 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1856 Constructor1Arg));
1857}
1858
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001859TEST(Matcher, ConstructorListInitialization) {
1860 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1861
1862 EXPECT_TRUE(
1863 matches("class X { public: X(int); }; void x() { X x{0}; }",
1864 ConstructorListInit));
1865 EXPECT_FALSE(
1866 matches("class X { public: X(int); }; void x() { X x(0); }",
1867 ConstructorListInit));
1868}
1869
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001870TEST(Matcher,ThisExpr) {
1871 EXPECT_TRUE(
1872 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1873 EXPECT_TRUE(
1874 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1875}
1876
Manuel Klimek04616e42012-07-06 05:48:52 +00001877TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001878 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001879
1880 std::string ClassString = "class string { public: string(); ~string(); }; ";
1881
1882 EXPECT_TRUE(
1883 matches(ClassString +
1884 "string GetStringByValue();"
1885 "void FunctionTakesString(string s);"
1886 "void run() { FunctionTakesString(GetStringByValue()); }",
1887 TempExpression));
1888
1889 EXPECT_TRUE(
1890 notMatches(ClassString +
1891 "string* GetStringPointer(); "
1892 "void FunctionTakesStringPtr(string* s);"
1893 "void run() {"
1894 " string* s = GetStringPointer();"
1895 " FunctionTakesStringPtr(GetStringPointer());"
1896 " FunctionTakesStringPtr(s);"
1897 "}",
1898 TempExpression));
1899
1900 EXPECT_TRUE(
1901 notMatches("class no_dtor {};"
1902 "no_dtor GetObjByValue();"
1903 "void ConsumeObj(no_dtor param);"
1904 "void run() { ConsumeObj(GetObjByValue()); }",
1905 TempExpression));
1906}
1907
Sam Panzer68a35af2012-08-24 22:04:44 +00001908TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1909 std::string ClassString =
1910 "class string { public: string(); int length(); }; ";
1911
1912 EXPECT_TRUE(
1913 matches(ClassString +
1914 "string GetStringByValue();"
1915 "void FunctionTakesString(string s);"
1916 "void run() { FunctionTakesString(GetStringByValue()); }",
1917 materializeTemporaryExpr()));
1918
1919 EXPECT_TRUE(
1920 notMatches(ClassString +
1921 "string* GetStringPointer(); "
1922 "void FunctionTakesStringPtr(string* s);"
1923 "void run() {"
1924 " string* s = GetStringPointer();"
1925 " FunctionTakesStringPtr(GetStringPointer());"
1926 " FunctionTakesStringPtr(s);"
1927 "}",
1928 materializeTemporaryExpr()));
1929
1930 EXPECT_TRUE(
1931 notMatches(ClassString +
1932 "string GetStringByValue();"
1933 "void run() { int k = GetStringByValue().length(); }",
1934 materializeTemporaryExpr()));
1935
1936 EXPECT_TRUE(
1937 notMatches(ClassString +
1938 "string GetStringByValue();"
1939 "void run() { GetStringByValue(); }",
1940 materializeTemporaryExpr()));
1941}
1942
Manuel Klimek04616e42012-07-06 05:48:52 +00001943TEST(ConstructorDeclaration, SimpleCase) {
1944 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001945 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001946 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001947 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001948}
1949
1950TEST(ConstructorDeclaration, IsImplicit) {
1951 // This one doesn't match because the constructor is not added by the
1952 // compiler (it is not needed).
1953 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001954 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001955 // The compiler added the implicit default constructor.
1956 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001957 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001958 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001959 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001960 // The compiler added an implicit assignment operator.
1961 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1962 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001963}
1964
Daniel Jasper1dad1832012-07-10 20:20:19 +00001965TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1966 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001967 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001968}
1969
1970TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001971 EXPECT_TRUE(notMatches("class Foo {};",
1972 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001973}
1974
Manuel Klimek04616e42012-07-06 05:48:52 +00001975TEST(HasAnyConstructorInitializer, SimpleCase) {
1976 EXPECT_TRUE(notMatches(
1977 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001978 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001979 EXPECT_TRUE(matches(
1980 "class Foo {"
1981 " Foo() : foo_() { }"
1982 " int foo_;"
1983 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001984 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001985}
1986
1987TEST(HasAnyConstructorInitializer, ForField) {
1988 static const char Code[] =
1989 "class Baz { };"
1990 "class Foo {"
1991 " Foo() : foo_() { }"
1992 " Baz foo_;"
1993 " Baz bar_;"
1994 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001995 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1996 forField(hasType(recordDecl(hasName("Baz"))))))));
1997 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001998 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001999 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
2000 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002001}
2002
2003TEST(HasAnyConstructorInitializer, WithInitializer) {
2004 static const char Code[] =
2005 "class Foo {"
2006 " Foo() : foo_(0) { }"
2007 " int foo_;"
2008 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002009 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002010 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002011 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002012 withInitializer(integerLiteral(equals(1)))))));
2013}
2014
2015TEST(HasAnyConstructorInitializer, IsWritten) {
2016 static const char Code[] =
2017 "struct Bar { Bar(){} };"
2018 "class Foo {"
2019 " Foo() : foo_() { }"
2020 " Bar foo_;"
2021 " Bar bar_;"
2022 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002023 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002024 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002025 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002026 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002027 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002028 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2029}
2030
2031TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002032 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002033
2034 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2035 EXPECT_TRUE(
2036 matches("class X { public: X(); }; void x() { new X(); }", New));
2037 EXPECT_TRUE(
2038 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2039 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2040}
2041
2042TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002043 StatementMatcher New = constructExpr(
2044 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002045
2046 EXPECT_TRUE(
2047 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2048 New));
2049 EXPECT_TRUE(
2050 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2051 New));
2052 EXPECT_TRUE(
2053 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2054 New));
2055
Daniel Jasper848cbe12012-09-18 13:09:13 +00002056 StatementMatcher WrongIndex = constructExpr(
2057 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002058 EXPECT_TRUE(
2059 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2060 WrongIndex));
2061}
2062
2063TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002064 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002065
2066 EXPECT_TRUE(
2067 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2068 EXPECT_TRUE(
2069 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2070 New));
2071}
2072
Daniel Jasper1dad1832012-07-10 20:20:19 +00002073TEST(Matcher, DeleteExpression) {
2074 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002075 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002076}
2077
Manuel Klimek04616e42012-07-06 05:48:52 +00002078TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002079 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002080
2081 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2082 EXPECT_TRUE(
2083 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2084 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2085}
2086
2087TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002088 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002089 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2090 // wide string
2091 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2092 // with escaped characters
2093 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2094 // no matching -- though the data type is the same, there is no string literal
2095 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2096}
2097
2098TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002099 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002100 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2101 // wide character
2102 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2103 // wide character, Hex encoded, NOT MATCHED!
2104 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2105 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2106}
2107
2108TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002109 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002110 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2111 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2112 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2113 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2114
2115 // Non-matching cases (character literals, float and double)
2116 EXPECT_TRUE(notMatches("int i = L'a';",
2117 HasIntLiteral)); // this is actually a character
2118 // literal cast to int
2119 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2120 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2121 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2122}
2123
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002124TEST(Matcher, FloatLiterals) {
2125 StatementMatcher HasFloatLiteral = floatLiteral();
2126 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2127 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2128 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2129 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2130 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002131 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2132 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2133 EXPECT_TRUE(
2134 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002135
2136 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002137 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2138 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2139 EXPECT_TRUE(
2140 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002141}
2142
Daniel Jasper5901e472012-10-01 13:40:41 +00002143TEST(Matcher, NullPtrLiteral) {
2144 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2145}
2146
Daniel Jasper87c3d362012-09-20 14:12:57 +00002147TEST(Matcher, AsmStatement) {
2148 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2149}
2150
Manuel Klimek04616e42012-07-06 05:48:52 +00002151TEST(Matcher, Conditions) {
2152 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2153
2154 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2155 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2156 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2157 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2158 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2159}
2160
Manuel Klimek909b5c942014-05-27 10:04:12 +00002161TEST(IfStmt, ChildTraversalMatchers) {
2162 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2163 ifStmt(hasThen(boolLiteral(equals(true))))));
2164 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2165 ifStmt(hasThen(boolLiteral(equals(true))))));
2166 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2167 ifStmt(hasElse(boolLiteral(equals(true))))));
2168 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2169 ifStmt(hasElse(boolLiteral(equals(true))))));
2170}
2171
Manuel Klimek04616e42012-07-06 05:48:52 +00002172TEST(MatchBinaryOperator, HasOperatorName) {
2173 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2174
2175 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2176 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2177}
2178
2179TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2180 StatementMatcher OperatorTrueFalse =
2181 binaryOperator(hasLHS(boolLiteral(equals(true))),
2182 hasRHS(boolLiteral(equals(false))));
2183
2184 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2185 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2186 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2187}
2188
2189TEST(MatchBinaryOperator, HasEitherOperand) {
2190 StatementMatcher HasOperand =
2191 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2192
2193 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2194 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2195 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2196}
2197
2198TEST(Matcher, BinaryOperatorTypes) {
2199 // Integration test that verifies the AST provides all binary operators in
2200 // a way we expect.
2201 // FIXME: Operator ','
2202 EXPECT_TRUE(
2203 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2204 EXPECT_TRUE(
2205 matches("bool b; bool c = (b = true);",
2206 binaryOperator(hasOperatorName("="))));
2207 EXPECT_TRUE(
2208 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2209 EXPECT_TRUE(
2210 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2211 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2212 EXPECT_TRUE(
2213 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2214 EXPECT_TRUE(
2215 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2216 EXPECT_TRUE(
2217 matches("int i = 1; int j = (i <<= 2);",
2218 binaryOperator(hasOperatorName("<<="))));
2219 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2220 EXPECT_TRUE(
2221 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2222 EXPECT_TRUE(
2223 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2224 EXPECT_TRUE(
2225 matches("int i = 1; int j = (i >>= 2);",
2226 binaryOperator(hasOperatorName(">>="))));
2227 EXPECT_TRUE(
2228 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2229 EXPECT_TRUE(
2230 matches("int i = 42; int j = (i ^= 42);",
2231 binaryOperator(hasOperatorName("^="))));
2232 EXPECT_TRUE(
2233 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2234 EXPECT_TRUE(
2235 matches("int i = 42; int j = (i %= 42);",
2236 binaryOperator(hasOperatorName("%="))));
2237 EXPECT_TRUE(
2238 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2239 EXPECT_TRUE(
2240 matches("bool b = true && false;",
2241 binaryOperator(hasOperatorName("&&"))));
2242 EXPECT_TRUE(
2243 matches("bool b = true; bool c = (b &= false);",
2244 binaryOperator(hasOperatorName("&="))));
2245 EXPECT_TRUE(
2246 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2247 EXPECT_TRUE(
2248 matches("bool b = true || false;",
2249 binaryOperator(hasOperatorName("||"))));
2250 EXPECT_TRUE(
2251 matches("bool b = true; bool c = (b |= false);",
2252 binaryOperator(hasOperatorName("|="))));
2253 EXPECT_TRUE(
2254 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2255 EXPECT_TRUE(
2256 matches("int i = 42; int j = (i *= 23);",
2257 binaryOperator(hasOperatorName("*="))));
2258 EXPECT_TRUE(
2259 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2260 EXPECT_TRUE(
2261 matches("int i = 42; int j = (i /= 23);",
2262 binaryOperator(hasOperatorName("/="))));
2263 EXPECT_TRUE(
2264 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2265 EXPECT_TRUE(
2266 matches("int i = 42; int j = (i += 23);",
2267 binaryOperator(hasOperatorName("+="))));
2268 EXPECT_TRUE(
2269 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2270 EXPECT_TRUE(
2271 matches("int i = 42; int j = (i -= 23);",
2272 binaryOperator(hasOperatorName("-="))));
2273 EXPECT_TRUE(
2274 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2275 binaryOperator(hasOperatorName("->*"))));
2276 EXPECT_TRUE(
2277 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2278 binaryOperator(hasOperatorName(".*"))));
2279
2280 // Member expressions as operators are not supported in matches.
2281 EXPECT_TRUE(
2282 notMatches("struct A { void x(A *a) { a->x(this); } };",
2283 binaryOperator(hasOperatorName("->"))));
2284
2285 // Initializer assignments are not represented as operator equals.
2286 EXPECT_TRUE(
2287 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2288
2289 // Array indexing is not represented as operator.
2290 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2291
2292 // Overloaded operators do not match at all.
2293 EXPECT_TRUE(notMatches(
2294 "struct A { bool operator&&(const A &a) const { return false; } };"
2295 "void x() { A a, b; a && b; }",
2296 binaryOperator()));
2297}
2298
2299TEST(MatchUnaryOperator, HasOperatorName) {
2300 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2301
2302 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2303 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2304}
2305
2306TEST(MatchUnaryOperator, HasUnaryOperand) {
2307 StatementMatcher OperatorOnFalse =
2308 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2309
2310 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2311 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2312}
2313
2314TEST(Matcher, UnaryOperatorTypes) {
2315 // Integration test that verifies the AST provides all unary operators in
2316 // a way we expect.
2317 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2318 EXPECT_TRUE(
2319 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2320 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2321 EXPECT_TRUE(
2322 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2323 EXPECT_TRUE(
2324 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2325 EXPECT_TRUE(
2326 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2327 EXPECT_TRUE(
2328 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2329 EXPECT_TRUE(
2330 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2331 EXPECT_TRUE(
2332 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2333 EXPECT_TRUE(
2334 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2335
2336 // We don't match conversion operators.
2337 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2338
2339 // Function calls are not represented as operator.
2340 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2341
2342 // Overloaded operators do not match at all.
2343 // FIXME: We probably want to add that.
2344 EXPECT_TRUE(notMatches(
2345 "struct A { bool operator!() const { return false; } };"
2346 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2347}
2348
2349TEST(Matcher, ConditionalOperator) {
2350 StatementMatcher Conditional = conditionalOperator(
2351 hasCondition(boolLiteral(equals(true))),
2352 hasTrueExpression(boolLiteral(equals(false))));
2353
2354 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2355 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2356 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2357
2358 StatementMatcher ConditionalFalse = conditionalOperator(
2359 hasFalseExpression(boolLiteral(equals(false))));
2360
2361 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2362 EXPECT_TRUE(
2363 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2364}
2365
Daniel Jasper1dad1832012-07-10 20:20:19 +00002366TEST(ArraySubscriptMatchers, ArraySubscripts) {
2367 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2368 arraySubscriptExpr()));
2369 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2370 arraySubscriptExpr()));
2371}
2372
2373TEST(ArraySubscriptMatchers, ArrayIndex) {
2374 EXPECT_TRUE(matches(
2375 "int i[2]; void f() { i[1] = 1; }",
2376 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2377 EXPECT_TRUE(matches(
2378 "int i[2]; void f() { 1[i] = 1; }",
2379 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2380 EXPECT_TRUE(notMatches(
2381 "int i[2]; void f() { i[1] = 1; }",
2382 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2383}
2384
2385TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2386 EXPECT_TRUE(matches(
2387 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002388 arraySubscriptExpr(hasBase(implicitCastExpr(
2389 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002390}
2391
Manuel Klimek04616e42012-07-06 05:48:52 +00002392TEST(Matcher, HasNameSupportsNamespaces) {
2393 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002394 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002395 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002396 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002397 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002398 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002399 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002400 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002401 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002402 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002403 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002404 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002405 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002406 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002407 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002408 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002409 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002410 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002411 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002412 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002413 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002414 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002415 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002416 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002417}
2418
2419TEST(Matcher, HasNameSupportsOuterClasses) {
2420 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002421 matches("class A { class B { class C; }; };",
2422 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002423 EXPECT_TRUE(
2424 matches("class A { class 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(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002427 matches("class A { class B { class C; }; };",
2428 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002429 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002430 matches("class A { class B { class C; }; };",
2431 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002432 EXPECT_TRUE(
2433 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002434 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002435 EXPECT_TRUE(
2436 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002437 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002438 EXPECT_TRUE(
2439 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002440 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002441 EXPECT_TRUE(
2442 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002443 recordDecl(hasName("::C"))));
2444 EXPECT_TRUE(
2445 notMatches("class A { class B { class C; }; };",
2446 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002447 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002448 recordDecl(hasName("z::A::B::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::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002452}
2453
2454TEST(Matcher, IsDefinition) {
2455 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002456 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002457 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2458 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2459
2460 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002461 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002462 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2463 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2464
2465 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002466 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002467 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2468 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2469}
2470
2471TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002472 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002473 ofClass(hasName("X")))));
2474
2475 EXPECT_TRUE(
2476 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2477 EXPECT_TRUE(
2478 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2479 Constructor));
2480 EXPECT_TRUE(
2481 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2482 Constructor));
2483}
2484
2485TEST(Matcher, VisitsTemplateInstantiations) {
2486 EXPECT_TRUE(matches(
2487 "class A { public: void x(); };"
2488 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002489 "void f() { B<A> b; b.y(); }",
2490 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002491
2492 EXPECT_TRUE(matches(
2493 "class A { public: void x(); };"
2494 "class C {"
2495 " public:"
2496 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2497 "};"
2498 "void f() {"
2499 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002500 "}",
2501 recordDecl(hasName("C"),
2502 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002503}
2504
Daniel Jasper1dad1832012-07-10 20:20:19 +00002505TEST(Matcher, HandlesNullQualTypes) {
2506 // FIXME: Add a Type matcher so we can replace uses of this
2507 // variable with Type(True())
2508 const TypeMatcher AnyType = anything();
2509
2510 // We don't really care whether this matcher succeeds; we're testing that
2511 // it completes without crashing.
2512 EXPECT_TRUE(matches(
2513 "struct A { };"
2514 "template <typename T>"
2515 "void f(T t) {"
2516 " T local_t(t /* this becomes a null QualType in the AST */);"
2517 "}"
2518 "void g() {"
2519 " f(0);"
2520 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002521 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002522 anyOf(
2523 TypeMatcher(hasDeclaration(anything())),
2524 pointsTo(AnyType),
2525 references(AnyType)
2526 // Other QualType matchers should go here.
2527 ))))));
2528}
2529
Manuel Klimek04616e42012-07-06 05:48:52 +00002530// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002531AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002532 // Make sure all special variables are used: node, match_finder,
2533 // bound_nodes_builder, and the parameter named 'AMatcher'.
2534 return AMatcher.matches(Node, Finder, Builder);
2535}
2536
2537TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002538 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002539
2540 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002541 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002542
2543 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002544 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002545
2546 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002547 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002548}
2549
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002550AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2551 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2552 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002553 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002554 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002555 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2556 ASTMatchFinder::BK_First);
2557}
2558
2559TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002560 DeclarationMatcher HasClassB =
2561 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002562
2563 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002564 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002565
2566 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002567 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002568
2569 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002570 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002571
2572 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002573 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002574
2575 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2576}
2577
2578TEST(For, FindsForLoops) {
2579 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2580 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002581 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2582 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002583 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002584}
2585
Daniel Jasper4e566c42012-07-12 08:50:38 +00002586TEST(For, ForLoopInternals) {
2587 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2588 forStmt(hasCondition(anything()))));
2589 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2590 forStmt(hasLoopInit(anything()))));
2591}
2592
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002593TEST(For, ForRangeLoopInternals) {
2594 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2595 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002596 EXPECT_TRUE(matches(
2597 "void f(){ int a[] {1, 2}; for (int i : a); }",
2598 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002599}
2600
Daniel Jasper4e566c42012-07-12 08:50:38 +00002601TEST(For, NegativeForLoopInternals) {
2602 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002603 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002604 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2605 forStmt(hasLoopInit(anything()))));
2606}
2607
Manuel Klimek04616e42012-07-06 05:48:52 +00002608TEST(For, ReportsNoFalsePositives) {
2609 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2610 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2611}
2612
2613TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002614 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2615 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2616 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002617}
2618
2619TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2620 // It's not a compound statement just because there's "{}" in the source
2621 // text. This is an AST search, not grep.
2622 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002623 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002624 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002625 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002626}
2627
Daniel Jasper4e566c42012-07-12 08:50:38 +00002628TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002629 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002630 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002631 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002632 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002633 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002634 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002635 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002636 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002637 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2638 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002639}
2640
2641TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2642 // The simplest case: every compound statement is in a function
2643 // definition, and the function body itself must be a compound
2644 // statement.
2645 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002646 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002647}
2648
2649TEST(HasAnySubstatement, IsNotRecursive) {
2650 // It's really "has any immediate substatement".
2651 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002652 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002653}
2654
2655TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2656 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002657 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002658}
2659
2660TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2661 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002662 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002663}
2664
2665TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2666 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002667 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002668 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002669 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002670}
2671
2672TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2673 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002674 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002675 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002676 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002677 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002678 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002679}
2680
2681TEST(StatementCountIs, WorksWithMultipleStatements) {
2682 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002683 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002684}
2685
2686TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2687 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002688 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002689 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002690 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002691 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002692 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002693 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002694 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002695}
2696
2697TEST(Member, WorksInSimplestCase) {
2698 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002699 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002700}
2701
2702TEST(Member, DoesNotMatchTheBaseExpression) {
2703 // Don't pick out the wrong part of the member expression, this should
2704 // be checking the member (name) only.
2705 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002706 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002707}
2708
2709TEST(Member, MatchesInMemberFunctionCall) {
2710 EXPECT_TRUE(matches("void f() {"
2711 " struct { void first() {}; } s;"
2712 " s.first();"
2713 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002714 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002715}
2716
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002717TEST(Member, MatchesMember) {
2718 EXPECT_TRUE(matches(
2719 "struct A { int i; }; void f() { A a; a.i = 2; }",
2720 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2721 EXPECT_TRUE(notMatches(
2722 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2723 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2724}
2725
Daniel Jasper639522c2013-02-25 12:02:08 +00002726TEST(Member, UnderstandsAccess) {
2727 EXPECT_TRUE(matches(
2728 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2729 EXPECT_TRUE(notMatches(
2730 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2731 EXPECT_TRUE(notMatches(
2732 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2733
2734 EXPECT_TRUE(notMatches(
2735 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2736 EXPECT_TRUE(notMatches(
2737 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2738 EXPECT_TRUE(matches(
2739 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2740
2741 EXPECT_TRUE(notMatches(
2742 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2743 EXPECT_TRUE(matches("class A { protected: int i; };",
2744 fieldDecl(isProtected(), hasName("i"))));
2745 EXPECT_TRUE(notMatches(
2746 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2747
2748 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2749 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2750 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2751 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2752}
2753
Dmitri Gribenko06963042012-08-18 00:29:27 +00002754TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002755 // Fails in C++11 mode
2756 EXPECT_TRUE(matchesConditionally(
2757 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2758 "class X { void *operator new(std::size_t); };",
2759 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002760
2761 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002762 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002763
Daniel Jasper5901e472012-10-01 13:40:41 +00002764 // Fails in C++11 mode
2765 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002766 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2767 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002768 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002769}
2770
Manuel Klimek04616e42012-07-06 05:48:52 +00002771TEST(HasObjectExpression, DoesNotMatchMember) {
2772 EXPECT_TRUE(notMatches(
2773 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002774 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002775}
2776
2777TEST(HasObjectExpression, MatchesBaseOfVariable) {
2778 EXPECT_TRUE(matches(
2779 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002780 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002781 EXPECT_TRUE(matches(
2782 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002783 memberExpr(hasObjectExpression(
2784 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002785}
2786
2787TEST(HasObjectExpression,
2788 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2789 EXPECT_TRUE(matches(
2790 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002791 memberExpr(hasObjectExpression(
2792 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002793 EXPECT_TRUE(matches(
2794 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002795 memberExpr(hasObjectExpression(
2796 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002797}
2798
2799TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002800 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2801 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2802 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2803 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002804}
2805
2806TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002807 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002808}
2809
2810TEST(IsConstQualified, MatchesConstInt) {
2811 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002812 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002813}
2814
2815TEST(IsConstQualified, MatchesConstPointer) {
2816 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002817 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002818}
2819
2820TEST(IsConstQualified, MatchesThroughTypedef) {
2821 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002822 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002823 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002824 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002825}
2826
2827TEST(IsConstQualified, DoesNotMatchInappropriately) {
2828 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002829 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002830 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002831 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002832}
2833
Sam Panzer80c13772012-08-16 16:58:10 +00002834TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002835 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2836 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2837 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2838 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002839}
2840TEST(CastExpression, MatchesImplicitCasts) {
2841 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002842 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002843 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002844 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002845}
2846
2847TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002848 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2849 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2850 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2851 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002852}
2853
Manuel Klimek04616e42012-07-06 05:48:52 +00002854TEST(ReinterpretCast, MatchesSimpleCase) {
2855 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002856 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002857}
2858
2859TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002860 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002861 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002862 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002863 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002864 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002865 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2866 "B b;"
2867 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002868 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002869}
2870
2871TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002872 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002873 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002874 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002875}
2876
2877TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002878 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002879 EXPECT_TRUE(
2880 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002881 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002882 EXPECT_TRUE(
2883 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002884 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002885}
2886
2887TEST(DynamicCast, MatchesSimpleCase) {
2888 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2889 "B b;"
2890 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002891 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002892}
2893
2894TEST(StaticCast, MatchesSimpleCase) {
2895 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002896 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002897}
2898
2899TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002900 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002901 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002902 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002903 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002904 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002905 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2906 "B b;"
2907 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002908 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002909}
2910
Daniel Jasper417f7762012-09-18 13:36:17 +00002911TEST(CStyleCast, MatchesSimpleCase) {
2912 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2913}
2914
2915TEST(CStyleCast, DoesNotMatchOtherCasts) {
2916 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2917 "char q, *r = const_cast<char*>(&q);"
2918 "void* s = reinterpret_cast<char*>(&s);"
2919 "struct B { virtual ~B() {} }; struct D : B {};"
2920 "B b;"
2921 "D* t = dynamic_cast<D*>(&b);",
2922 cStyleCastExpr()));
2923}
2924
Manuel Klimek04616e42012-07-06 05:48:52 +00002925TEST(HasDestinationType, MatchesSimpleCase) {
2926 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002927 staticCastExpr(hasDestinationType(
2928 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002929}
2930
Sam Panzer80c13772012-08-16 16:58:10 +00002931TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2932 // This test creates an implicit const cast.
2933 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002934 implicitCastExpr(
2935 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002936 // This test creates an implicit array-to-pointer cast.
2937 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002938 implicitCastExpr(hasImplicitDestinationType(
2939 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002940}
2941
2942TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2943 // This test creates an implicit cast from int to char.
2944 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002945 implicitCastExpr(hasImplicitDestinationType(
2946 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002947 // This test creates an implicit array-to-pointer cast.
2948 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002949 implicitCastExpr(hasImplicitDestinationType(
2950 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002951}
2952
2953TEST(ImplicitCast, MatchesSimpleCase) {
2954 // This test creates an implicit const cast.
2955 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002956 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002957 // This test creates an implicit cast from int to char.
2958 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002959 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002960 // This test creates an implicit array-to-pointer cast.
2961 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002962 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002963}
2964
2965TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002966 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002967 // are present, and that it ignores explicit and paren casts.
2968
2969 // These two test cases have no casts.
2970 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002971 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002972 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002973 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002974
2975 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002976 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002977 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002978 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002979
2980 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002981 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002982}
2983
2984TEST(IgnoringImpCasts, MatchesImpCasts) {
2985 // This test checks that ignoringImpCasts matches when implicit casts are
2986 // present and its inner matcher alone does not match.
2987 // Note that this test creates an implicit const cast.
2988 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002989 varDecl(hasInitializer(ignoringImpCasts(
2990 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002991 // This test creates an implict cast from int to char.
2992 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002993 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002994 integerLiteral(equals(0)))))));
2995}
2996
2997TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2998 // These tests verify that ignoringImpCasts does not match if the inner
2999 // matcher does not match.
3000 // Note that the first test creates an implicit const cast.
3001 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003002 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003003 unless(anything()))))));
3004 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003005 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003006 unless(anything()))))));
3007
3008 // These tests verify that ignoringImplictCasts does not look through explicit
3009 // casts or parentheses.
3010 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003011 varDecl(hasInitializer(ignoringImpCasts(
3012 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003013 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003014 varDecl(hasInitializer(ignoringImpCasts(
3015 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003016 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003017 varDecl(hasInitializer(ignoringImpCasts(
3018 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003019 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003020 varDecl(hasInitializer(ignoringImpCasts(
3021 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003022}
3023
3024TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3025 // This test verifies that expressions that do not have implicit casts
3026 // still match the inner matcher.
3027 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003028 varDecl(hasInitializer(ignoringImpCasts(
3029 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003030}
3031
3032TEST(IgnoringParenCasts, MatchesParenCasts) {
3033 // This test checks that ignoringParenCasts matches when parentheses and/or
3034 // casts are present and its inner matcher alone does not match.
3035 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003036 varDecl(hasInitializer(ignoringParenCasts(
3037 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003038 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003039 varDecl(hasInitializer(ignoringParenCasts(
3040 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003041
3042 // This test creates an implict cast from int to char in addition to the
3043 // parentheses.
3044 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003045 varDecl(hasInitializer(ignoringParenCasts(
3046 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003047
3048 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003049 varDecl(hasInitializer(ignoringParenCasts(
3050 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003051 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003052 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003053 integerLiteral(equals(0)))))));
3054}
3055
3056TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3057 // This test verifies that expressions that do not have any casts still match.
3058 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003059 varDecl(hasInitializer(ignoringParenCasts(
3060 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003061}
3062
3063TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3064 // These tests verify that ignoringImpCasts does not match if the inner
3065 // matcher does not match.
3066 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003067 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003068 unless(anything()))))));
3069
3070 // This test creates an implicit cast from int to char in addition to the
3071 // parentheses.
3072 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003073 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003074 unless(anything()))))));
3075
3076 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003077 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003078 unless(anything()))))));
3079}
3080
3081TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3082 // This test checks that ignoringParenAndImpCasts matches when
3083 // parentheses and/or implicit casts are present and its inner matcher alone
3084 // does not match.
3085 // Note that this test creates an implicit const cast.
3086 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003087 varDecl(hasInitializer(ignoringParenImpCasts(
3088 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003089 // This test creates an implicit cast from int to char.
3090 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003091 varDecl(hasInitializer(ignoringParenImpCasts(
3092 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003093}
3094
3095TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3096 // This test verifies that expressions that do not have parentheses or
3097 // implicit casts still match.
3098 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003099 varDecl(hasInitializer(ignoringParenImpCasts(
3100 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003101 EXPECT_TRUE(matches("int 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, DoesNotMatchIncorrectly) {
3107 // These tests verify that ignoringParenImpCasts does not match if
3108 // the inner matcher does not match.
3109 // This test creates an implicit cast.
3110 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003111 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003112 unless(anything()))))));
3113 // These tests verify that ignoringParenAndImplictCasts does not look
3114 // through explicit casts.
3115 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003116 varDecl(hasInitializer(ignoringParenImpCasts(
3117 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003118 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003119 varDecl(hasInitializer(ignoringParenImpCasts(
3120 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003121 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003122 varDecl(hasInitializer(ignoringParenImpCasts(
3123 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003124}
3125
Manuel Klimeke9235692012-07-25 10:02:02 +00003126TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003127 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3128 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003129 implicitCastExpr(
3130 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003131}
3132
Manuel Klimeke9235692012-07-25 10:02:02 +00003133TEST(HasSourceExpression, MatchesExplicitCasts) {
3134 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003135 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003136 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003137 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003138}
3139
Manuel Klimek04616e42012-07-06 05:48:52 +00003140TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003141 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003142}
3143
3144TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003145 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003146}
3147
3148TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003149 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003150}
3151
3152TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003153 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003154}
3155
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003156TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3157 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3158 "const Foo f = Foo();",
3159 varDecl(hasInitializer(exprWithCleanups()))));
3160 EXPECT_FALSE(matches("struct Foo { };"
3161 "const Foo f = Foo();",
3162 varDecl(hasInitializer(exprWithCleanups()))));
3163}
3164
Daniel Jasper1dad1832012-07-10 20:20:19 +00003165TEST(InitListExpression, MatchesInitListExpression) {
3166 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3167 initListExpr(hasType(asString("int [2]")))));
3168 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003169 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003170 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3171 "void f();"
3172 "S s[1] = { &f };",
3173 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003174 EXPECT_TRUE(
3175 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003176}
3177
3178TEST(UsingDeclaration, MatchesUsingDeclarations) {
3179 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3180 usingDecl()));
3181}
3182
3183TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3184 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3185 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3186}
3187
3188TEST(UsingDeclaration, MatchesSpecificTarget) {
3189 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3190 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003191 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003192 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3193 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003194 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003195}
3196
3197TEST(UsingDeclaration, ThroughUsingDeclaration) {
3198 EXPECT_TRUE(matches(
3199 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003200 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003201 EXPECT_TRUE(notMatches(
3202 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003203 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003204}
3205
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003206TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3207 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3208 usingDirectiveDecl()));
3209 EXPECT_FALSE(
3210 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3211}
3212
Sam Panzerd624bfb2012-08-16 17:20:59 +00003213TEST(SingleDecl, IsSingleDecl) {
3214 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003215 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003216 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3217 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3218 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3219 SingleDeclStmt));
3220}
3221
3222TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003223 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003224
3225 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003226 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003227 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003228 declStmt(containsDeclaration(0, MatchesInit),
3229 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003230 unsigned WrongIndex = 42;
3231 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003232 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003233 MatchesInit))));
3234}
3235
3236TEST(DeclCount, DeclCountIsCorrect) {
3237 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003238 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003239 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003240 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003241 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003242 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003243}
3244
Manuel Klimek04616e42012-07-06 05:48:52 +00003245TEST(While, MatchesWhileLoops) {
3246 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3247 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3248 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3249}
3250
3251TEST(Do, MatchesDoLoops) {
3252 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3253 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3254}
3255
3256TEST(Do, DoesNotMatchWhileLoops) {
3257 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3258}
3259
3260TEST(SwitchCase, MatchesCase) {
3261 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3262 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3263 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3264 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3265}
3266
Daniel Jasper87c3d362012-09-20 14:12:57 +00003267TEST(SwitchCase, MatchesSwitch) {
3268 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3269 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3270 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3271 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3272}
3273
Peter Collingbourne3154a102013-05-10 11:52:02 +00003274TEST(SwitchCase, MatchesEachCase) {
3275 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3276 switchStmt(forEachSwitchCase(caseStmt()))));
3277 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3278 switchStmt(forEachSwitchCase(caseStmt()))));
3279 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3280 switchStmt(forEachSwitchCase(caseStmt()))));
3281 EXPECT_TRUE(notMatches(
3282 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3283 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3284 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3285 switchStmt(forEachSwitchCase(
3286 caseStmt(hasCaseConstant(integerLiteral()))))));
3287 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3288 switchStmt(forEachSwitchCase(
3289 caseStmt(hasCaseConstant(integerLiteral()))))));
3290 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3291 switchStmt(forEachSwitchCase(
3292 caseStmt(hasCaseConstant(integerLiteral()))))));
3293 EXPECT_TRUE(matchAndVerifyResultTrue(
3294 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3295 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3296 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3297}
3298
Manuel Klimekba46fc02013-07-19 11:50:54 +00003299TEST(ForEachConstructorInitializer, MatchesInitializers) {
3300 EXPECT_TRUE(matches(
3301 "struct X { X() : i(42), j(42) {} int i, j; };",
3302 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3303}
3304
Daniel Jasper87c3d362012-09-20 14:12:57 +00003305TEST(ExceptionHandling, SimpleCases) {
3306 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3307 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3308 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3309 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3310 throwExpr()));
3311 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3312 throwExpr()));
3313}
3314
Manuel Klimek04616e42012-07-06 05:48:52 +00003315TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3316 EXPECT_TRUE(notMatches(
3317 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003318 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003319 EXPECT_TRUE(notMatches(
3320 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003321 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003322}
3323
3324TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3325 EXPECT_TRUE(matches(
3326 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003327 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003328}
3329
3330TEST(ForEach, BindsOneNode) {
3331 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003332 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003333 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003334}
3335
3336TEST(ForEach, BindsMultipleNodes) {
3337 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003338 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003339 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003340}
3341
3342TEST(ForEach, BindsRecursiveCombinations) {
3343 EXPECT_TRUE(matchAndVerifyResultTrue(
3344 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003345 recordDecl(hasName("C"),
3346 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003347 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003348}
3349
3350TEST(ForEachDescendant, BindsOneNode) {
3351 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003352 recordDecl(hasName("C"),
3353 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003354 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003355}
3356
Daniel Jasper94a56852012-11-16 18:39:22 +00003357TEST(ForEachDescendant, NestedForEachDescendant) {
3358 DeclarationMatcher m = recordDecl(
3359 isDefinition(), decl().bind("x"), hasName("C"));
3360 EXPECT_TRUE(matchAndVerifyResultTrue(
3361 "class A { class B { class C {}; }; };",
3362 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3363 new VerifyIdIsBoundTo<Decl>("x", "C")));
3364
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003365 // Check that a partial match of 'm' that binds 'x' in the
3366 // first part of anyOf(m, anything()) will not overwrite the
3367 // binding created by the earlier binding in the hasDescendant.
3368 EXPECT_TRUE(matchAndVerifyResultTrue(
3369 "class A { class B { class C {}; }; };",
3370 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3371 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003372}
3373
Manuel Klimek04616e42012-07-06 05:48:52 +00003374TEST(ForEachDescendant, BindsMultipleNodes) {
3375 EXPECT_TRUE(matchAndVerifyResultTrue(
3376 "class C { class D { int x; int y; }; "
3377 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003378 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003379 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003380}
3381
3382TEST(ForEachDescendant, BindsRecursiveCombinations) {
3383 EXPECT_TRUE(matchAndVerifyResultTrue(
3384 "class C { class D { "
3385 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003386 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3387 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003388 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003389}
3390
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003391TEST(ForEachDescendant, BindsCombinations) {
3392 EXPECT_TRUE(matchAndVerifyResultTrue(
3393 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3394 "(true) {} }",
3395 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3396 forEachDescendant(whileStmt().bind("while"))),
3397 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3398}
3399
3400TEST(Has, DoesNotDeleteBindings) {
3401 EXPECT_TRUE(matchAndVerifyResultTrue(
3402 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3403 new VerifyIdIsBoundTo<Decl>("x", 1)));
3404}
3405
3406TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3407 // Those matchers cover all the cases where an inner matcher is called
3408 // and there is not a 1:1 relationship between the match of the outer
3409 // matcher and the match of the inner matcher.
3410 // The pattern to look for is:
3411 // ... return InnerMatcher.matches(...); ...
3412 // In which case no special handling is needed.
3413 //
3414 // On the other hand, if there are multiple alternative matches
3415 // (for example forEach*) or matches might be discarded (for example has*)
3416 // the implementation must make sure that the discarded matches do not
3417 // affect the bindings.
3418 // When new such matchers are added, add a test here that:
3419 // - matches a simple node, and binds it as the first thing in the matcher:
3420 // recordDecl(decl().bind("x"), hasName("X")))
3421 // - uses the matcher under test afterwards in a way that not the first
3422 // alternative is matched; for anyOf, that means the first branch
3423 // would need to return false; for hasAncestor, it means that not
3424 // the direct parent matches the inner matcher.
3425
3426 EXPECT_TRUE(matchAndVerifyResultTrue(
3427 "class X { int y; };",
3428 recordDecl(
3429 recordDecl().bind("x"), hasName("::X"),
3430 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3431 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3432 EXPECT_TRUE(matchAndVerifyResultTrue(
3433 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3434 anyOf(unless(anything()), anything())),
3435 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3436 EXPECT_TRUE(matchAndVerifyResultTrue(
3437 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3438 classTemplateSpecializationDecl(
3439 decl().bind("x"),
3440 hasAnyTemplateArgument(refersToType(asString("int")))),
3441 new VerifyIdIsBoundTo<Decl>("x", 1)));
3442 EXPECT_TRUE(matchAndVerifyResultTrue(
3443 "class X { void f(); void g(); };",
3444 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3445 new VerifyIdIsBoundTo<Decl>("x", 1)));
3446 EXPECT_TRUE(matchAndVerifyResultTrue(
3447 "class X { X() : a(1), b(2) {} double a; int b; };",
3448 recordDecl(decl().bind("x"),
3449 has(constructorDecl(
3450 hasAnyConstructorInitializer(forField(hasName("b")))))),
3451 new VerifyIdIsBoundTo<Decl>("x", 1)));
3452 EXPECT_TRUE(matchAndVerifyResultTrue(
3453 "void x(int, int) { x(0, 42); }",
3454 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3455 new VerifyIdIsBoundTo<Expr>("x", 1)));
3456 EXPECT_TRUE(matchAndVerifyResultTrue(
3457 "void x(int, int y) {}",
3458 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3459 new VerifyIdIsBoundTo<Decl>("x", 1)));
3460 EXPECT_TRUE(matchAndVerifyResultTrue(
3461 "void x() { return; if (true) {} }",
3462 functionDecl(decl().bind("x"),
3463 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3464 new VerifyIdIsBoundTo<Decl>("x", 1)));
3465 EXPECT_TRUE(matchAndVerifyResultTrue(
3466 "namespace X { void b(int); void b(); }"
3467 "using X::b;",
3468 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3469 functionDecl(parameterCountIs(1))))),
3470 new VerifyIdIsBoundTo<Decl>("x", 1)));
3471 EXPECT_TRUE(matchAndVerifyResultTrue(
3472 "class A{}; class B{}; class C : B, A {};",
3473 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3474 new VerifyIdIsBoundTo<Decl>("x", 1)));
3475 EXPECT_TRUE(matchAndVerifyResultTrue(
3476 "class A{}; typedef A B; typedef A C; typedef A D;"
3477 "class E : A {};",
3478 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3479 new VerifyIdIsBoundTo<Decl>("x", 1)));
3480 EXPECT_TRUE(matchAndVerifyResultTrue(
3481 "class A { class B { void f() {} }; };",
3482 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3483 new VerifyIdIsBoundTo<Decl>("x", 1)));
3484 EXPECT_TRUE(matchAndVerifyResultTrue(
3485 "template <typename T> struct A { struct B {"
3486 " void f() { if(true) {} }"
3487 "}; };"
3488 "void t() { A<int>::B b; b.f(); }",
3489 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3490 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3491 EXPECT_TRUE(matchAndVerifyResultTrue(
3492 "class A {};",
3493 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3494 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003495 EXPECT_TRUE(matchAndVerifyResultTrue(
3496 "class A { A() : s(), i(42) {} const char *s; int i; };",
3497 constructorDecl(hasName("::A::A"), decl().bind("x"),
3498 forEachConstructorInitializer(forField(hasName("i")))),
3499 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003500}
3501
Daniel Jasper33806cd2012-11-11 22:14:55 +00003502TEST(ForEachDescendant, BindsCorrectNodes) {
3503 EXPECT_TRUE(matchAndVerifyResultTrue(
3504 "class C { void f(); int i; };",
3505 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3506 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3507 EXPECT_TRUE(matchAndVerifyResultTrue(
3508 "class C { void f() {} int i; };",
3509 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3510 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3511}
3512
Manuel Klimekabf43712013-02-04 10:59:20 +00003513TEST(FindAll, BindsNodeOnMatch) {
3514 EXPECT_TRUE(matchAndVerifyResultTrue(
3515 "class A {};",
3516 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3517 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3518}
3519
3520TEST(FindAll, BindsDescendantNodeOnMatch) {
3521 EXPECT_TRUE(matchAndVerifyResultTrue(
3522 "class A { int a; int b; };",
3523 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3524 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3525}
3526
3527TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3528 EXPECT_TRUE(matchAndVerifyResultTrue(
3529 "class A { int a; int b; };",
3530 recordDecl(hasName("::A"),
3531 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3532 fieldDecl().bind("v"))))),
3533 new VerifyIdIsBoundTo<Decl>("v", 3)));
3534
3535 EXPECT_TRUE(matchAndVerifyResultTrue(
3536 "class A { class B {}; class C {}; };",
3537 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3538 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3539}
3540
Manuel Klimek88b95872013-02-04 09:42:38 +00003541TEST(EachOf, TriggersForEachMatch) {
3542 EXPECT_TRUE(matchAndVerifyResultTrue(
3543 "class A { int a; int b; };",
3544 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3545 has(fieldDecl(hasName("b")).bind("v")))),
3546 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3547}
3548
3549TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3550 EXPECT_TRUE(matchAndVerifyResultTrue(
3551 "class A { int a; int c; };",
3552 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3553 has(fieldDecl(hasName("b")).bind("v")))),
3554 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3555 EXPECT_TRUE(matchAndVerifyResultTrue(
3556 "class A { int c; int b; };",
3557 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3558 has(fieldDecl(hasName("b")).bind("v")))),
3559 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3560 EXPECT_TRUE(notMatches(
3561 "class A { int c; int d; };",
3562 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3563 has(fieldDecl(hasName("b")).bind("v"))))));
3564}
Manuel Klimek04616e42012-07-06 05:48:52 +00003565
3566TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3567 // Make sure that we can both match the class by name (::X) and by the type
3568 // the template was instantiated with (via a field).
3569
3570 EXPECT_TRUE(matches(
3571 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003572 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003573
3574 EXPECT_TRUE(matches(
3575 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003576 recordDecl(isTemplateInstantiation(), hasDescendant(
3577 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003578}
3579
3580TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3581 EXPECT_TRUE(matches(
3582 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003583 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003584 isTemplateInstantiation())));
3585}
3586
3587TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3588 EXPECT_TRUE(matches(
3589 "template <typename T> class X { T t; }; class A {};"
3590 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003591 recordDecl(isTemplateInstantiation(), hasDescendant(
3592 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003593}
3594
3595TEST(IsTemplateInstantiation,
3596 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3597 EXPECT_TRUE(matches(
3598 "template <typename T> class X {};"
3599 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003600 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003601}
3602
3603TEST(IsTemplateInstantiation,
3604 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3605 EXPECT_TRUE(matches(
3606 "class A {};"
3607 "class X {"
3608 " template <typename U> class Y { U u; };"
3609 " Y<A> y;"
3610 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003611 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003612}
3613
3614TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3615 // FIXME: Figure out whether this makes sense. It doesn't affect the
3616 // normal use case as long as the uppermost instantiation always is marked
3617 // as template instantiation, but it might be confusing as a predicate.
3618 EXPECT_TRUE(matches(
3619 "class A {};"
3620 "template <typename T> class X {"
3621 " template <typename U> class Y { U u; };"
3622 " Y<T> y;"
3623 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003624 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003625}
3626
3627TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3628 EXPECT_TRUE(notMatches(
3629 "template <typename T> class X {}; class A {};"
3630 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003631 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003632}
3633
3634TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3635 EXPECT_TRUE(notMatches(
3636 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003637 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003638}
3639
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003640TEST(IsInstantiated, MatchesInstantiation) {
3641 EXPECT_TRUE(
3642 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3643 recordDecl(isInstantiated())));
3644}
3645
3646TEST(IsInstantiated, NotMatchesDefinition) {
3647 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3648 recordDecl(isInstantiated())));
3649}
3650
3651TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3652 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3653 "class Y { A<int> a; }; Y y;",
3654 declStmt(isInTemplateInstantiation())));
3655}
3656
3657TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3658 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3659 declStmt(isInTemplateInstantiation())));
3660}
3661
3662TEST(IsInstantiated, MatchesFunctionInstantiation) {
3663 EXPECT_TRUE(
3664 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3665 functionDecl(isInstantiated())));
3666}
3667
3668TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3669 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3670 varDecl(isInstantiated())));
3671}
3672
3673TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3674 EXPECT_TRUE(
3675 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3676 declStmt(isInTemplateInstantiation())));
3677}
3678
3679TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3680 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3681 declStmt(isInTemplateInstantiation())));
3682}
3683
3684TEST(IsInTemplateInstantiation, Sharing) {
3685 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3686 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3687 // and makes the matcher behave in non-obvious ways.
3688 EXPECT_TRUE(notMatches(
3689 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3690 Matcher));
3691 EXPECT_TRUE(matches(
3692 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3693 Matcher));
3694}
3695
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003696TEST(IsExplicitTemplateSpecialization,
3697 DoesNotMatchPrimaryTemplate) {
3698 EXPECT_TRUE(notMatches(
3699 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003700 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003701 EXPECT_TRUE(notMatches(
3702 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003703 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003704}
3705
3706TEST(IsExplicitTemplateSpecialization,
3707 DoesNotMatchExplicitTemplateInstantiations) {
3708 EXPECT_TRUE(notMatches(
3709 "template <typename T> class X {};"
3710 "template class X<int>; extern template class X<long>;",
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) {}"
3714 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003715 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003716}
3717
3718TEST(IsExplicitTemplateSpecialization,
3719 DoesNotMatchImplicitTemplateInstantiations) {
3720 EXPECT_TRUE(notMatches(
3721 "template <typename T> class X {}; X<int> x;",
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); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003725 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003726}
3727
3728TEST(IsExplicitTemplateSpecialization,
3729 MatchesExplicitTemplateSpecializations) {
3730 EXPECT_TRUE(matches(
3731 "template <typename T> class X {};"
3732 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003733 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003734 EXPECT_TRUE(matches(
3735 "template <typename T> void f(T t) {}"
3736 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003737 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003738}
3739
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003740TEST(HasAncenstor, MatchesDeclarationAncestors) {
3741 EXPECT_TRUE(matches(
3742 "class A { class B { class C {}; }; };",
3743 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3744}
3745
3746TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3747 EXPECT_TRUE(notMatches(
3748 "class A { class B { class C {}; }; };",
3749 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3750}
3751
3752TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3753 EXPECT_TRUE(matches(
3754 "class A { class B { void f() { C c; } class C {}; }; };",
3755 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3756 hasAncestor(recordDecl(hasName("A"))))))));
3757}
3758
3759TEST(HasAncenstor, MatchesStatementAncestors) {
3760 EXPECT_TRUE(matches(
3761 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003762 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003763}
3764
3765TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3766 EXPECT_TRUE(matches(
3767 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003768 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003769}
3770
3771TEST(HasAncestor, BindsRecursiveCombinations) {
3772 EXPECT_TRUE(matchAndVerifyResultTrue(
3773 "class C { class D { class E { class F { int y; }; }; }; };",
3774 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003775 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003776}
3777
3778TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3779 EXPECT_TRUE(matchAndVerifyResultTrue(
3780 "class C { class D { class E { class F { int y; }; }; }; };",
3781 fieldDecl(hasAncestor(
3782 decl(
3783 hasDescendant(recordDecl(isDefinition(),
3784 hasAncestor(recordDecl())))
3785 ).bind("d")
3786 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003787 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003788}
3789
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003790TEST(HasAncestor, MatchesClosestAncestor) {
3791 EXPECT_TRUE(matchAndVerifyResultTrue(
3792 "template <typename T> struct C {"
3793 " void f(int) {"
3794 " struct I { void g(T) { int x; } } i; i.g(42);"
3795 " }"
3796 "};"
3797 "template struct C<int>;",
3798 varDecl(hasName("x"),
3799 hasAncestor(functionDecl(hasParameter(
3800 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3801 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3802}
3803
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003804TEST(HasAncestor, MatchesInTemplateInstantiations) {
3805 EXPECT_TRUE(matches(
3806 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3807 "A<int>::B::C a;",
3808 fieldDecl(hasType(asString("int")),
3809 hasAncestor(recordDecl(hasName("A"))))));
3810}
3811
3812TEST(HasAncestor, MatchesInImplicitCode) {
3813 EXPECT_TRUE(matches(
3814 "struct X {}; struct A { A() {} X x; };",
3815 constructorDecl(
3816 hasAnyConstructorInitializer(withInitializer(expr(
3817 hasAncestor(recordDecl(hasName("A")))))))));
3818}
3819
Daniel Jasper632aea92012-10-22 16:26:51 +00003820TEST(HasParent, MatchesOnlyParent) {
3821 EXPECT_TRUE(matches(
3822 "void f() { if (true) { int x = 42; } }",
3823 compoundStmt(hasParent(ifStmt()))));
3824 EXPECT_TRUE(notMatches(
3825 "void f() { for (;;) { int x = 42; } }",
3826 compoundStmt(hasParent(ifStmt()))));
3827 EXPECT_TRUE(notMatches(
3828 "void f() { if (true) for (;;) { int x = 42; } }",
3829 compoundStmt(hasParent(ifStmt()))));
3830}
3831
Manuel Klimekc844a462012-12-06 14:42:48 +00003832TEST(HasAncestor, MatchesAllAncestors) {
3833 EXPECT_TRUE(matches(
3834 "template <typename T> struct C { static void f() { 42; } };"
3835 "void t() { C<int>::f(); }",
3836 integerLiteral(
3837 equals(42),
3838 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3839 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3840}
3841
3842TEST(HasParent, MatchesAllParents) {
3843 EXPECT_TRUE(matches(
3844 "template <typename T> struct C { static void f() { 42; } };"
3845 "void t() { C<int>::f(); }",
3846 integerLiteral(
3847 equals(42),
3848 hasParent(compoundStmt(hasParent(functionDecl(
3849 hasParent(recordDecl(isTemplateInstantiation())))))))));
3850 EXPECT_TRUE(matches(
3851 "template <typename T> struct C { static void f() { 42; } };"
3852 "void t() { C<int>::f(); }",
3853 integerLiteral(
3854 equals(42),
3855 hasParent(compoundStmt(hasParent(functionDecl(
3856 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3857 EXPECT_TRUE(matches(
3858 "template <typename T> struct C { static void f() { 42; } };"
3859 "void t() { C<int>::f(); }",
3860 integerLiteral(equals(42),
3861 hasParent(compoundStmt(allOf(
3862 hasParent(functionDecl(
3863 hasParent(recordDecl(isTemplateInstantiation())))),
3864 hasParent(functionDecl(hasParent(recordDecl(
3865 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003866 EXPECT_TRUE(
3867 notMatches("template <typename T> struct C { static void f() {} };"
3868 "void t() { C<int>::f(); }",
3869 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003870}
3871
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003872TEST(HasParent, NoDuplicateParents) {
3873 class HasDuplicateParents : public BoundNodesCallback {
3874 public:
3875 bool run(const BoundNodes *Nodes) override { return false; }
3876 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3877 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3878 std::set<const void *> Parents;
3879 for (const auto &Parent : Context->getParents(*Node)) {
3880 if (!Parents.insert(Parent.getMemoizationData()).second) {
3881 return true;
3882 }
3883 }
3884 return false;
3885 }
3886 };
3887 EXPECT_FALSE(matchAndVerifyResultTrue(
3888 "template <typename T> int Foo() { return 1 + 2; }\n"
3889 "int x = Foo<int>() + Foo<unsigned>();",
3890 stmt().bind("node"), new HasDuplicateParents()));
3891}
3892
Daniel Jasper516b02e2012-10-17 08:52:59 +00003893TEST(TypeMatching, MatchesTypes) {
3894 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3895}
3896
Samuel Benzaquenb405c082014-12-15 15:09:22 +00003897TEST(TypeMatching, MatchesVoid) {
3898 EXPECT_TRUE(
3899 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
3900}
3901
Daniel Jasper516b02e2012-10-17 08:52:59 +00003902TEST(TypeMatching, MatchesArrayTypes) {
3903 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3904 EXPECT_TRUE(matches("int a[42];", arrayType()));
3905 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3906
3907 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3908 arrayType(hasElementType(builtinType()))));
3909
3910 EXPECT_TRUE(matches(
3911 "int const a[] = { 2, 3 };",
3912 qualType(arrayType(hasElementType(builtinType())))));
3913 EXPECT_TRUE(matches(
3914 "int const a[] = { 2, 3 };",
3915 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3916 EXPECT_TRUE(matches(
3917 "typedef const int T; T x[] = { 1, 2 };",
3918 qualType(isConstQualified(), arrayType())));
3919
3920 EXPECT_TRUE(notMatches(
3921 "int a[] = { 2, 3 };",
3922 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3923 EXPECT_TRUE(notMatches(
3924 "int a[] = { 2, 3 };",
3925 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3926 EXPECT_TRUE(notMatches(
3927 "int const a[] = { 2, 3 };",
3928 qualType(arrayType(hasElementType(builtinType())),
3929 unless(isConstQualified()))));
3930
3931 EXPECT_TRUE(matches("int a[2];",
3932 constantArrayType(hasElementType(builtinType()))));
3933 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3934}
3935
3936TEST(TypeMatching, MatchesComplexTypes) {
3937 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3938 EXPECT_TRUE(matches(
3939 "_Complex float f;",
3940 complexType(hasElementType(builtinType()))));
3941 EXPECT_TRUE(notMatches(
3942 "_Complex float f;",
3943 complexType(hasElementType(isInteger()))));
3944}
3945
3946TEST(TypeMatching, MatchesConstantArrayTypes) {
3947 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3948 EXPECT_TRUE(notMatches(
3949 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3950 constantArrayType(hasElementType(builtinType()))));
3951
3952 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3953 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3954 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3955}
3956
3957TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3958 EXPECT_TRUE(matches(
3959 "template <typename T, int Size> class array { T data[Size]; };",
3960 dependentSizedArrayType()));
3961 EXPECT_TRUE(notMatches(
3962 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3963 dependentSizedArrayType()));
3964}
3965
3966TEST(TypeMatching, MatchesIncompleteArrayType) {
3967 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3968 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3969
3970 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3971 incompleteArrayType()));
3972}
3973
3974TEST(TypeMatching, MatchesVariableArrayType) {
3975 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3976 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3977
3978 EXPECT_TRUE(matches(
3979 "void f(int b) { int a[b]; }",
3980 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3981 varDecl(hasName("b")))))))));
3982}
3983
3984TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003985 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3986 llvm::Triple::Win32) {
3987 // FIXME: Make this work for MSVC.
3988 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003989
David Majnemer197e2102014-03-05 06:32:38 +00003990 EXPECT_TRUE(matches("_Atomic(int) i;",
3991 atomicType(hasValueType(isInteger()))));
3992 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3993 atomicType(hasValueType(isInteger()))));
3994 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003995}
3996
3997TEST(TypeMatching, MatchesAutoTypes) {
3998 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3999 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4000 autoType()));
4001
Richard Smith061f1e22013-04-30 21:23:01 +00004002 // FIXME: Matching against the type-as-written can't work here, because the
4003 // type as written was not deduced.
4004 //EXPECT_TRUE(matches("auto a = 1;",
4005 // autoType(hasDeducedType(isInteger()))));
4006 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4007 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004008}
4009
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004010TEST(TypeMatching, MatchesFunctionTypes) {
4011 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4012 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4013}
4014
Edwin Vaneec074802013-04-01 18:33:34 +00004015TEST(TypeMatching, MatchesParenType) {
4016 EXPECT_TRUE(
4017 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4018 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4019
4020 EXPECT_TRUE(matches(
4021 "int (*ptr_to_func)(int);",
4022 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4023 EXPECT_TRUE(notMatches(
4024 "int (*ptr_to_array)[4];",
4025 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4026}
4027
Daniel Jasper516b02e2012-10-17 08:52:59 +00004028TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004029 // FIXME: Reactive when these tests can be more specific (not matching
4030 // implicit code on certain platforms), likely when we have hasDescendant for
4031 // Types/TypeLocs.
4032 //EXPECT_TRUE(matchAndVerifyResultTrue(
4033 // "int* a;",
4034 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4035 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4036 //EXPECT_TRUE(matchAndVerifyResultTrue(
4037 // "int* a;",
4038 // pointerTypeLoc().bind("loc"),
4039 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004040 EXPECT_TRUE(matches(
4041 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004042 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004043 EXPECT_TRUE(matches(
4044 "int** a;",
4045 loc(pointerType(pointee(pointerType())))));
4046 EXPECT_TRUE(matches(
4047 "int* b; int* * const a = &b;",
4048 loc(qualType(isConstQualified(), pointerType()))));
4049
4050 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004051 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4052 hasType(blockPointerType()))));
4053 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4054 hasType(memberPointerType()))));
4055 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4056 hasType(pointerType()))));
4057 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4058 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004059 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4060 hasType(lValueReferenceType()))));
4061 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4062 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004063
Daniel Jasper7943eb52012-10-17 13:35:36 +00004064 Fragment = "int *ptr;";
4065 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4066 hasType(blockPointerType()))));
4067 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4068 hasType(memberPointerType()))));
4069 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4070 hasType(pointerType()))));
4071 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4072 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004073
Daniel Jasper7943eb52012-10-17 13:35:36 +00004074 Fragment = "int a; int &ref = a;";
4075 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4076 hasType(blockPointerType()))));
4077 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4078 hasType(memberPointerType()))));
4079 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4080 hasType(pointerType()))));
4081 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4082 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004083 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4084 hasType(lValueReferenceType()))));
4085 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4086 hasType(rValueReferenceType()))));
4087
4088 Fragment = "int &&ref = 2;";
4089 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4090 hasType(blockPointerType()))));
4091 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4092 hasType(memberPointerType()))));
4093 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4094 hasType(pointerType()))));
4095 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4096 hasType(referenceType()))));
4097 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4098 hasType(lValueReferenceType()))));
4099 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4100 hasType(rValueReferenceType()))));
4101}
4102
4103TEST(TypeMatching, AutoRefTypes) {
4104 std::string Fragment = "auto a = 1;"
4105 "auto b = a;"
4106 "auto &c = a;"
4107 "auto &&d = c;"
4108 "auto &&e = 2;";
4109 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4110 hasType(referenceType()))));
4111 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4112 hasType(referenceType()))));
4113 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4114 hasType(referenceType()))));
4115 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4116 hasType(lValueReferenceType()))));
4117 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4118 hasType(rValueReferenceType()))));
4119 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4120 hasType(referenceType()))));
4121 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4122 hasType(lValueReferenceType()))));
4123 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4124 hasType(rValueReferenceType()))));
4125 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4126 hasType(referenceType()))));
4127 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4128 hasType(lValueReferenceType()))));
4129 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4130 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004131}
4132
4133TEST(TypeMatching, PointeeTypes) {
4134 EXPECT_TRUE(matches("int b; int &a = b;",
4135 referenceType(pointee(builtinType()))));
4136 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4137
4138 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004139 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004140
4141 EXPECT_TRUE(matches(
4142 "int const *A;",
4143 pointerType(pointee(isConstQualified(), builtinType()))));
4144 EXPECT_TRUE(notMatches(
4145 "int *A;",
4146 pointerType(pointee(isConstQualified(), builtinType()))));
4147}
4148
4149TEST(TypeMatching, MatchesPointersToConstTypes) {
4150 EXPECT_TRUE(matches("int b; int * const a = &b;",
4151 loc(pointerType())));
4152 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004153 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004154 EXPECT_TRUE(matches(
4155 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004156 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004157 EXPECT_TRUE(matches(
4158 "int b; const int * a = &b;",
4159 pointerType(pointee(builtinType()))));
4160}
4161
4162TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004163 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4164 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004165}
4166
Edwin Vanef901b712013-02-25 14:49:29 +00004167TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004168 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004169 templateSpecializationType()));
4170}
4171
Edwin Vaneb6eae142013-02-25 20:43:32 +00004172TEST(TypeMatching, MatchesRecordType) {
4173 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004174 EXPECT_TRUE(matches("struct S{}; S s;",
4175 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4176 EXPECT_TRUE(notMatches("int i;",
4177 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004178}
4179
4180TEST(TypeMatching, MatchesElaboratedType) {
4181 EXPECT_TRUE(matches(
4182 "namespace N {"
4183 " namespace M {"
4184 " class D {};"
4185 " }"
4186 "}"
4187 "N::M::D d;", elaboratedType()));
4188 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4189 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4190}
4191
4192TEST(ElaboratedTypeNarrowing, hasQualifier) {
4193 EXPECT_TRUE(matches(
4194 "namespace N {"
4195 " namespace M {"
4196 " class D {};"
4197 " }"
4198 "}"
4199 "N::M::D d;",
4200 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4201 EXPECT_TRUE(notMatches(
4202 "namespace M {"
4203 " class D {};"
4204 "}"
4205 "M::D d;",
4206 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004207 EXPECT_TRUE(notMatches(
4208 "struct D {"
4209 "} d;",
4210 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004211}
4212
4213TEST(ElaboratedTypeNarrowing, namesType) {
4214 EXPECT_TRUE(matches(
4215 "namespace N {"
4216 " namespace M {"
4217 " class D {};"
4218 " }"
4219 "}"
4220 "N::M::D d;",
4221 elaboratedType(elaboratedType(namesType(recordType(
4222 hasDeclaration(namedDecl(hasName("D")))))))));
4223 EXPECT_TRUE(notMatches(
4224 "namespace M {"
4225 " class D {};"
4226 "}"
4227 "M::D d;",
4228 elaboratedType(elaboratedType(namesType(typedefType())))));
4229}
4230
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004231TEST(NNS, MatchesNestedNameSpecifiers) {
4232 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4233 nestedNameSpecifier()));
4234 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4235 nestedNameSpecifier()));
4236 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4237 nestedNameSpecifier()));
4238
4239 EXPECT_TRUE(matches(
4240 "struct A { static void f() {} }; void g() { A::f(); }",
4241 nestedNameSpecifier()));
4242 EXPECT_TRUE(notMatches(
4243 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4244 nestedNameSpecifier()));
4245}
4246
Daniel Jasper87c3d362012-09-20 14:12:57 +00004247TEST(NullStatement, SimpleCases) {
4248 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4249 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4250}
4251
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004252TEST(NNS, MatchesTypes) {
4253 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4254 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4255 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4256 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4257 Matcher));
4258 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4259}
4260
4261TEST(NNS, MatchesNamespaceDecls) {
4262 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4263 specifiesNamespace(hasName("ns")));
4264 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4265 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4266 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4267}
4268
4269TEST(NNS, BindsNestedNameSpecifiers) {
4270 EXPECT_TRUE(matchAndVerifyResultTrue(
4271 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4272 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4273 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4274}
4275
4276TEST(NNS, BindsNestedNameSpecifierLocs) {
4277 EXPECT_TRUE(matchAndVerifyResultTrue(
4278 "namespace ns { struct B {}; } ns::B b;",
4279 loc(nestedNameSpecifier()).bind("loc"),
4280 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4281}
4282
4283TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4284 EXPECT_TRUE(matches(
4285 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4286 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4287 EXPECT_TRUE(matches(
4288 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004289 nestedNameSpecifierLoc(hasPrefix(
4290 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004291}
4292
Daniel Jasper6fc34332012-10-30 15:42:00 +00004293TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4294 std::string Fragment =
4295 "namespace a { struct A { struct B { struct C {}; }; }; };"
4296 "void f() { a::A::B::C c; }";
4297 EXPECT_TRUE(matches(
4298 Fragment,
4299 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4300 hasDescendant(nestedNameSpecifier(
4301 specifiesNamespace(hasName("a")))))));
4302 EXPECT_TRUE(notMatches(
4303 Fragment,
4304 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4305 has(nestedNameSpecifier(
4306 specifiesNamespace(hasName("a")))))));
4307 EXPECT_TRUE(matches(
4308 Fragment,
4309 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4310 has(nestedNameSpecifier(
4311 specifiesNamespace(hasName("a")))))));
4312
4313 // Not really useful because a NestedNameSpecifier can af at most one child,
4314 // but to complete the interface.
4315 EXPECT_TRUE(matchAndVerifyResultTrue(
4316 Fragment,
4317 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4318 forEach(nestedNameSpecifier().bind("x"))),
4319 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4320}
4321
4322TEST(NNS, NestedNameSpecifiersAsDescendants) {
4323 std::string Fragment =
4324 "namespace a { struct A { struct B { struct C {}; }; }; };"
4325 "void f() { a::A::B::C c; }";
4326 EXPECT_TRUE(matches(
4327 Fragment,
4328 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4329 asString("struct a::A")))))));
4330 EXPECT_TRUE(matchAndVerifyResultTrue(
4331 Fragment,
4332 functionDecl(hasName("f"),
4333 forEachDescendant(nestedNameSpecifier().bind("x"))),
4334 // Nested names: a, a::A and a::A::B.
4335 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4336}
4337
4338TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4339 std::string Fragment =
4340 "namespace a { struct A { struct B { struct C {}; }; }; };"
4341 "void f() { a::A::B::C c; }";
4342 EXPECT_TRUE(matches(
4343 Fragment,
4344 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4345 hasDescendant(loc(nestedNameSpecifier(
4346 specifiesNamespace(hasName("a"))))))));
4347 EXPECT_TRUE(notMatches(
4348 Fragment,
4349 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4350 has(loc(nestedNameSpecifier(
4351 specifiesNamespace(hasName("a"))))))));
4352 EXPECT_TRUE(matches(
4353 Fragment,
4354 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4355 has(loc(nestedNameSpecifier(
4356 specifiesNamespace(hasName("a"))))))));
4357
4358 EXPECT_TRUE(matchAndVerifyResultTrue(
4359 Fragment,
4360 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4361 forEach(nestedNameSpecifierLoc().bind("x"))),
4362 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4363}
4364
4365TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4366 std::string Fragment =
4367 "namespace a { struct A { struct B { struct C {}; }; }; };"
4368 "void f() { a::A::B::C c; }";
4369 EXPECT_TRUE(matches(
4370 Fragment,
4371 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4372 asString("struct a::A"))))))));
4373 EXPECT_TRUE(matchAndVerifyResultTrue(
4374 Fragment,
4375 functionDecl(hasName("f"),
4376 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4377 // Nested names: a, a::A and a::A::B.
4378 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4379}
4380
Manuel Klimek191c0932013-02-01 13:41:35 +00004381template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004382public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004383 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4384 StringRef InnerId)
4385 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004386 }
4387
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004388 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004389
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004390 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004391 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004392 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4393 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004394 }
4395private:
4396 std::string Id;
4397 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004398 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004399};
4400
4401TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004402 EXPECT_TRUE(matchAndVerifyResultTrue(
4403 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4404 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004405 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4406 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004407 EXPECT_TRUE(matchAndVerifyResultFalse(
4408 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4409 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004410 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4411 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004412}
4413
4414TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004415 EXPECT_TRUE(matchAndVerifyResultTrue(
4416 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004417 new VerifyMatchOnNode<clang::Stmt>(
4418 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004419 EXPECT_TRUE(matchAndVerifyResultFalse(
4420 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004421 new VerifyMatchOnNode<clang::Stmt>(
4422 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004423}
4424
4425TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4426 EXPECT_TRUE(matchAndVerifyResultTrue(
4427 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4428 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004429 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004430 EXPECT_TRUE(matchAndVerifyResultFalse(
4431 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4432 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004433 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004434}
4435
Manuel Klimekbee08572013-02-07 12:42:10 +00004436template <typename T>
4437class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4438public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004439 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004440
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004441 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004442 const T *Node = Nodes->getNodeAs<T>("");
4443 return verify(*Nodes, *Context, Node);
4444 }
4445
4446 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004447 // Use the original typed pointer to verify we can pass pointers to subtypes
4448 // to equalsNode.
4449 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004450 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004451 "", match(stmt(hasParent(
4452 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004453 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004454 }
4455 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004456 // Use the original typed pointer to verify we can pass pointers to subtypes
4457 // to equalsNode.
4458 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004459 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004460 "", match(decl(hasParent(
4461 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004462 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004463 }
4464};
4465
4466TEST(IsEqualTo, MatchesNodesByIdentity) {
4467 EXPECT_TRUE(matchAndVerifyResultTrue(
4468 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004469 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4470 EXPECT_TRUE(matchAndVerifyResultTrue(
4471 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4472 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004473}
4474
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004475TEST(MatchFinder, CheckProfiling) {
4476 MatchFinder::MatchFinderOptions Options;
4477 llvm::StringMap<llvm::TimeRecord> Records;
4478 Options.CheckProfiling.emplace(Records);
4479 MatchFinder Finder(std::move(Options));
4480
4481 struct NamedCallback : public MatchFinder::MatchCallback {
4482 void run(const MatchFinder::MatchResult &Result) override {}
4483 StringRef getID() const override { return "MyID"; }
4484 } Callback;
4485 Finder.addMatcher(decl(), &Callback);
4486 std::unique_ptr<FrontendActionFactory> Factory(
4487 newFrontendActionFactory(&Finder));
4488 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4489
4490 EXPECT_EQ(1u, Records.size());
4491 EXPECT_EQ("MyID", Records.begin()->getKey());
4492}
4493
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004494class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4495public:
4496 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004497 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004498 EXPECT_TRUE(Called);
4499 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004500 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004501 bool Called;
4502};
4503
4504TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4505 MatchFinder Finder;
4506 VerifyStartOfTranslationUnit VerifyCallback;
4507 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004508 std::unique_ptr<FrontendActionFactory> Factory(
4509 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004510 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4511 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004512
4513 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004514 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004515 ASSERT_TRUE(AST.get());
4516 Finder.matchAST(AST->getASTContext());
4517 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004518}
4519
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004520class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4521public:
4522 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004523 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004524 EXPECT_FALSE(Called);
4525 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004526 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004527 bool Called;
4528};
4529
4530TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4531 MatchFinder Finder;
4532 VerifyEndOfTranslationUnit VerifyCallback;
4533 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004534 std::unique_ptr<FrontendActionFactory> Factory(
4535 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004536 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4537 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004538
4539 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004540 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004541 ASSERT_TRUE(AST.get());
4542 Finder.matchAST(AST->getASTContext());
4543 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004544}
4545
Manuel Klimekbbb75852013-06-20 14:06:32 +00004546TEST(EqualsBoundNodeMatcher, QualType) {
4547 EXPECT_TRUE(matches(
4548 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4549 hasInitializer(ignoringParenImpCasts(
4550 hasType(qualType(equalsBoundNode("type"))))))));
4551 EXPECT_TRUE(notMatches("int i = 1.f;",
4552 varDecl(hasType(qualType().bind("type")),
4553 hasInitializer(ignoringParenImpCasts(hasType(
4554 qualType(equalsBoundNode("type"))))))));
4555}
4556
4557TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4558 EXPECT_TRUE(notMatches(
4559 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4560 hasInitializer(ignoringParenImpCasts(
4561 hasType(qualType(equalsBoundNode("type"))))))));
4562}
4563
4564TEST(EqualsBoundNodeMatcher, Stmt) {
4565 EXPECT_TRUE(
4566 matches("void f() { if(true) {} }",
4567 stmt(allOf(ifStmt().bind("if"),
4568 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4569
4570 EXPECT_TRUE(notMatches(
4571 "void f() { if(true) { if (true) {} } }",
4572 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4573}
4574
4575TEST(EqualsBoundNodeMatcher, Decl) {
4576 EXPECT_TRUE(matches(
4577 "class X { class Y {}; };",
4578 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4579 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4580
4581 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4582 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4583 has(decl(equalsBoundNode("record")))))));
4584}
4585
4586TEST(EqualsBoundNodeMatcher, Type) {
4587 EXPECT_TRUE(matches(
4588 "class X { int a; int b; };",
4589 recordDecl(
4590 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4591 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4592
4593 EXPECT_TRUE(notMatches(
4594 "class X { int a; double b; };",
4595 recordDecl(
4596 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4597 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4598}
4599
4600TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004601 EXPECT_TRUE(matchAndVerifyResultTrue(
4602 "int f() {"
4603 " if (1) {"
4604 " int i = 9;"
4605 " }"
4606 " int j = 10;"
4607 " {"
4608 " float k = 9.0;"
4609 " }"
4610 " return 0;"
4611 "}",
4612 // Look for variable declarations within functions whose type is the same
4613 // as the function return type.
4614 functionDecl(returns(qualType().bind("type")),
4615 forEachDescendant(varDecl(hasType(
4616 qualType(equalsBoundNode("type")))).bind("decl"))),
4617 // Only i and j should match, not k.
4618 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4619}
4620
4621TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4622 EXPECT_TRUE(matchAndVerifyResultTrue(
4623 "void f() {"
4624 " int x;"
4625 " double d;"
4626 " x = d + x - d + x;"
4627 "}",
4628 functionDecl(
4629 hasName("f"), forEachDescendant(varDecl().bind("d")),
4630 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4631 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4632}
4633
Manuel Klimekce68f772014-03-25 14:39:26 +00004634TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4635 EXPECT_TRUE(matchAndVerifyResultTrue(
4636 "struct StringRef { int size() const; const char* data() const; };"
4637 "void f(StringRef v) {"
4638 " v.data();"
4639 "}",
4640 memberCallExpr(
4641 callee(methodDecl(hasName("data"))),
4642 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4643 .bind("var")))),
4644 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4645 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4646 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4647 .bind("data"),
4648 new VerifyIdIsBoundTo<Expr>("data", 1)));
4649
4650 EXPECT_FALSE(matches(
4651 "struct StringRef { int size() const; const char* data() const; };"
4652 "void f(StringRef v) {"
4653 " v.data();"
4654 " v.size();"
4655 "}",
4656 memberCallExpr(
4657 callee(methodDecl(hasName("data"))),
4658 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4659 .bind("var")))),
4660 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4661 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4662 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4663 .bind("data")));
4664}
4665
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004666TEST(TypeDefDeclMatcher, Match) {
4667 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4668 typedefDecl(hasName("typedefDeclTest"))));
4669}
4670
4671// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4672#ifndef LLVM_ON_WIN32
4673
4674TEST(Matcher, IsExpansionInMainFileMatcher) {
4675 EXPECT_TRUE(matches("class X {};",
4676 recordDecl(hasName("X"), isExpansionInMainFile())));
4677 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4678 FileContentMappings M;
4679 M.push_back(std::make_pair("/other", "class X {};"));
4680 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4681 recordDecl(isExpansionInMainFile()), false,
4682 "-isystem/", M));
4683}
4684
4685TEST(Matcher, IsExpansionInSystemHeader) {
4686 FileContentMappings M;
4687 M.push_back(std::make_pair("/other", "class X {};"));
4688 EXPECT_TRUE(matchesConditionally(
4689 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4690 "-isystem/", M));
4691 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4692 recordDecl(isExpansionInSystemHeader()),
4693 false, "-I/", M));
4694 EXPECT_TRUE(notMatches("class X {};",
4695 recordDecl(isExpansionInSystemHeader())));
4696 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4697}
4698
4699TEST(Matcher, IsExpansionInFileMatching) {
4700 FileContentMappings M;
4701 M.push_back(std::make_pair("/foo", "class A {};"));
4702 M.push_back(std::make_pair("/bar", "class B {};"));
4703 EXPECT_TRUE(matchesConditionally(
4704 "#include <foo>\n"
4705 "#include <bar>\n"
4706 "class X {};",
4707 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4708 "-isystem/", M));
4709 EXPECT_TRUE(matchesConditionally(
4710 "#include <foo>\n"
4711 "#include <bar>\n"
4712 "class X {};",
4713 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4714 "-isystem/", M));
4715}
4716
4717#endif // LLVM_ON_WIN32
4718
Manuel Klimekbfa43572015-03-12 15:48:15 +00004719
4720TEST(ObjCMessageExprMatcher, SimpleExprs) {
4721 // don't find ObjCMessageExpr where none are present
4722 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
4723
4724 std::string Objc1String =
4725 "@interface Str "
4726 " - (Str *)uppercaseString:(Str *)str;"
4727 "@end "
4728 "@interface foo "
4729 "- (void)meth:(Str *)text;"
4730 "@end "
4731 " "
4732 "@implementation foo "
4733 "- (void) meth:(Str *)text { "
4734 " [self contents];"
4735 " Str *up = [text uppercaseString];"
4736 "} "
4737 "@end ";
4738 EXPECT_TRUE(matchesObjC(
4739 Objc1String,
4740 objcMessageExpr(anything())));
4741 EXPECT_TRUE(matchesObjC(
4742 Objc1String,
4743 objcMessageExpr(hasSelector("contents"))));
4744 EXPECT_TRUE(matchesObjC(
4745 Objc1String,
4746 objcMessageExpr(matchesSelector("cont*"))));
4747 EXPECT_FALSE(matchesObjC(
4748 Objc1String,
4749 objcMessageExpr(matchesSelector("?cont*"))));
4750 EXPECT_TRUE(notMatchesObjC(
4751 Objc1String,
4752 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
4753 EXPECT_TRUE(matchesObjC(
4754 Objc1String,
4755 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
4756 EXPECT_TRUE(matchesObjC(
4757 Objc1String,
4758 objcMessageExpr(matchesSelector("uppercase*"),
4759 argumentCountIs(0)
4760 )));
4761
4762}
4763
Manuel Klimek04616e42012-07-06 05:48:52 +00004764} // end namespace ast_matchers
4765} // end namespace clang