blob: 0d27b5db0348be24a72e3720c0020b3bcd11b772 [file] [log] [blame]
Manuel Klimek4da21662012-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 Kramer8b9ed712012-12-01 17:22:05 +000011#include "clang/AST/PrettyPrinter.h"
Manuel Klimek4da21662012-07-06 05:48:52 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Chandler Carruth1050e8b2012-12-04 09:45:34 +000013#include "clang/ASTMatchers/ASTMatchers.h"
Manuel Klimek4da21662012-07-06 05:48:52 +000014#include "clang/Tooling/Tooling.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070015#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
Manuel Klimek4da21662012-07-06 05:48:52 +000017#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
Benjamin Kramer78a0ce42012-07-10 17:30:44 +000022#if GTEST_HAS_DEATH_TEST
Manuel Klimek4da21662012-07-06 05:48:52 +000023TEST(HasNameDeathTest, DiesOnEmptyName) {
24 ASSERT_DEBUG_DEATH({
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000025 DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
Manuel Klimek4da21662012-07-06 05:48:52 +000026 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27 }, "");
28}
29
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000030TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31 ASSERT_DEBUG_DEATH({
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000032 DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000033 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34 }, "");
35}
36
Manuel Klimek4da21662012-07-06 05:48:52 +000037TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38 ASSERT_DEBUG_DEATH({
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000039 DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
Manuel Klimek4da21662012-07-06 05:48:52 +000040 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41 }, "");
42}
Benjamin Kramer78a0ce42012-07-10 17:30:44 +000043#endif
Manuel Klimek4da21662012-07-06 05:48:52 +000044
Peter Collingbourned2bd5892013-11-07 22:30:32 +000045TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46 MatchFinder Finder;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070047 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50 nullptr));
Peter Collingbourned2bd5892013-11-07 22:30:32 +000051
52 // Do not accept non-toplevel matchers.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070053 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54 EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
Peter Collingbourned2bd5892013-11-07 22:30:32 +000056}
57
Manuel Klimek715c9562012-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 Klimek4da21662012-07-06 05:48:52 +000064TEST(NameableDeclaration, MatchesVariousDecls) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000065 DeclarationMatcher NamedX = namedDecl(hasName("X"));
Manuel Klimek4da21662012-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 Jaspere0e6b9e2012-07-10 20:20:19 +000072 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
Manuel Klimek4da21662012-07-06 05:48:52 +000073
74 EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000077TEST(NameableDeclaration, REMatchesVariousDecls) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000078 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
Daniel Jaspere0e6b9e2012-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 Jasper2dc75ed2012-08-24 05:12:34 +000089 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
Daniel Jaspere0e6b9e2012-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 Jasper2dc75ed2012-08-24 05:12:34 +000093 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
Daniel Jaspere0e6b9e2012-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 Klimekec33b6f2012-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 Jaspere0e6b9e2012-07-10 20:20:19 +0000105}
106
Manuel Klimek4da21662012-07-06 05:48:52 +0000107TEST(DeclarationMatcher, MatchClass) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000108 DeclarationMatcher ClassMatcher(recordDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -0700109 llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110 if (Triple.getOS() != llvm::Triple::Win32 ||
111 Triple.getEnvironment() != llvm::Triple::MSVC)
112 EXPECT_FALSE(matches("", ClassMatcher));
113 else
114 // Matches class type_info.
115 EXPECT_TRUE(matches("", ClassMatcher));
Manuel Klimek4da21662012-07-06 05:48:52 +0000116
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000117 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000125 DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000126
127 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
Daniel Jasper76dafa72012-09-07 12:48:17 +0000128 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
Manuel Klimek4da21662012-07-06 05:48:52 +0000130 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131 EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
Daniel Jasper63d88722012-09-12 21:14:15 +0000133 DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
Daniel Jasper76dafa72012-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 Klimek4da21662012-07-06 05:48:52 +0000141 DeclarationMatcher ZIsDerivedFromX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000142 recordDecl(hasName("Z"), isDerivedFrom("X"));
Manuel Klimek4da21662012-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 Klimek987c2f52012-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 Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000284 varDecl(hasName("z_float"),
285 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000286 EXPECT_TRUE(notMatches(
287 RecursiveTemplateOneParameter,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000288 varDecl(hasName("z_float"),
289 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000290 EXPECT_TRUE(matches(
291 RecursiveTemplateOneParameter,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000292 varDecl(hasName("z_char"),
293 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
294 isDerivedFrom("Base2")))))));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000309 varDecl(hasName("z_float"),
310 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000311 EXPECT_TRUE(notMatches(
312 RecursiveTemplateTwoParameters,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000313 varDecl(hasName("z_float"),
314 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000315 EXPECT_TRUE(matches(
316 RecursiveTemplateTwoParameters,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000317 varDecl(hasName("z_char"),
318 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
319 isDerivedFrom("Base2")))))));
Daniel Jasper20b802d2012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000322 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper20b802d2012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000325 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper20b802d2012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000329 recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
Manuel Klimekb56da8c2013-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 Klimek4da21662012-07-06 05:48:52 +0000336}
337
Edwin Vane6a19a972013-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 Jasper08f0c532012-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 Vane742d9e72013-02-25 20:43:32 +0000355TEST(DeclarationMatcher, hasDeclContext) {
356 EXPECT_TRUE(matches(
357 "namespace N {"
358 " namespace M {"
359 " class D {};"
360 " }"
361 "}",
Daniel Jasperabe92232013-04-08 16:44:05 +0000362 recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
Edwin Vane742d9e72013-02-25 20:43:32 +0000363 EXPECT_TRUE(notMatches(
364 "namespace N {"
365 " namespace M {"
366 " class D {};"
367 " }"
368 "}",
Daniel Jasperabe92232013-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()))))));
Stephen Hines176edba2014-12-01 14:53:08 -0800378
379 EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
380}
381
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700382TEST(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
Stephen Hines176edba2014-12-01 14:53:08 -0800397TEST(DeclarationMatcher, LinkageSpecification) {
398 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
399 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
Edwin Vane742d9e72013-02-25 20:43:32 +0000400}
401
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000402TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000403 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenko8456ae62012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000409 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenko8456ae62012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000417 classTemplateDecl(hasName("X"),
418 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenko8456ae62012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000424 classTemplateDecl(hasName("X"),
425 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000426}
427
Daniel Jasper6a124492012-07-12 08:50:38 +0000428TEST(AllOf, AllOverloadsWork) {
429 const char Program[] =
Edwin Vane7f43fcf2013-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 Jasper6a124492012-07-12 08:50:38 +0000433 EXPECT_TRUE(matches(Program,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000434 callExpr(allOf(callee(functionDecl(hasName("f"))),
435 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper6a124492012-07-12 08:50:38 +0000436 EXPECT_TRUE(matches(Program,
Daniel Jasper2dc75ed2012-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 Vane7f43fcf2013-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 Jasper6a124492012-07-12 08:50:38 +0000454}
455
Manuel Klimek4da21662012-07-06 05:48:52 +0000456TEST(DeclarationMatcher, MatchAnyOf) {
457 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000458 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek4da21662012-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 Jasperff2fcb82012-07-15 19:57:12 +0000466 DeclarationMatcher XOrYOrZOrU =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000467 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasperff2fcb82012-07-15 19:57:12 +0000468 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
469 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
470
Manuel Klimek4da21662012-07-06 05:48:52 +0000471 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000472 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
473 hasName("V")));
Manuel Klimek4da21662012-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));
Stephen Hines176edba2014-12-01 14:53:08 -0800480
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 Klimek4da21662012-07-06 05:48:52 +0000485}
486
487TEST(DeclarationMatcher, MatchHas) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000488 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000493 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000502 recordDecl(
503 has(recordDecl(
504 has(recordDecl(hasName("X"))),
505 has(recordDecl(hasName("Y"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000506 hasName("Z"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000507 has(recordDecl(
508 has(recordDecl(hasName("A"))),
509 has(recordDecl(hasName("B"))),
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000560 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000561 anyOf(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000562 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000563 anyOf(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000564 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000565 hasName("X"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000566 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000567 hasName("Y"))),
568 hasName("Z")))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000569 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000570 anyOf(
571 hasName("C"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000572 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000573 hasName("A"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000574 has(recordDecl(
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000591 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000592 isDerivedFrom("Y"),
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000603 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000604 hasName("X"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000605 has(recordDecl(hasName("Z"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000606 unless(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000607 has(recordDecl(hasName("Y")))));
Manuel Klimek4da21662012-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));
Stephen Hines176edba2014-12-01 14:53:08 -0800611
612 DeclarationMatcher NamedNotRecord =
613 namedDecl(hasName("Foo"), unless(recordDecl()));
614 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
615 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek4da21662012-07-06 05:48:52 +0000616}
617
618TEST(DeclarationMatcher, HasDescendant) {
619 DeclarationMatcher ZDescendantClassX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000620 recordDecl(
621 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000635 recordDecl(
636 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000658 recordDecl(
659 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
660 hasName("X"))),
Manuel Klimek4da21662012-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
Stephen Hines176edba2014-12-01 14:53:08 -0800678TEST(DeclarationMatcher, HasDescendantMemoization) {
679 DeclarationMatcher CannotMemoize =
680 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
681 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
682}
683
684TEST(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
698TEST(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
705TEST(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() {}",
710 hasAttr(clang::attr::CUDADevice)));
711 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
712 CUDAKernelCallExpr()));
713 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
714 hasAttr(clang::attr::CUDAGlobal)));
715}
716
Daniel Jaspera267cf62012-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 Klimek374516c2013-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 Jaspera267cf62012-10-29 10:14:44 +0000740
Stephen Hines651f13c2014-04-23 16:59:28 -0700741 void onEndOfTranslationUnit() override {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000742 if (ExpectedCount != -1)
743 EXPECT_EQ(ExpectedCount, Count);
744 if (!ExpectedName.empty())
745 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourned2bd5892013-11-07 22:30:32 +0000746 Count = 0;
747 Name.clear();
748 }
749
750 ~VerifyIdIsBoundTo() {
751 EXPECT_EQ(0, Count);
752 EXPECT_EQ("", Name);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000753 }
754
Stephen Hines176edba2014-12-01 14:53:08 -0800755 virtual bool run(const BoundNodes *Nodes) override {
Peter Collingbourne3f0e0402013-11-06 00:27:07 +0000756 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jaspera267cf62012-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 Collingbourne3f0e0402013-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 Jaspera267cf62012-10-29 10:14:44 +0000770 return true;
771 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700772 EXPECT_TRUE(M.count(Id) == 0 ||
773 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000774 return false;
775 }
776
Stephen Hines176edba2014-12-01 14:53:08 -0800777 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jasper452abbc2012-10-29 10:48:25 +0000778 return run(Nodes);
779 }
780
Daniel Jaspera267cf62012-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 Blaikie5be093c2013-02-18 19:04:16 +0000817 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jaspera267cf62012-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
Stephen Hines176edba2014-12-01 14:53:08 -0800845TEST(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 Jaspere0e6b9e2012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000861 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jaspere0e6b9e2012-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 Klimek4da21662012-07-06 05:48:52 +0000867TEST(StatementMatcher, Has) {
868 StatementMatcher HasVariableI =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000869 expr(hasType(pointsTo(recordDecl(hasName("X")))),
870 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000880 expr(hasType(pointsTo(recordDecl(hasName("X")))),
881 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000892 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000897 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +0000904 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000905
906 EXPECT_TRUE(
907 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
908}
909
Manuel Klimek4da21662012-07-06 05:48:52 +0000910TEST(Matcher, BindMatchedNodes) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000911 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000912
913 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera7564432012-09-13 13:11:25 +0000914 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000915
916 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera7564432012-09-13 13:11:25 +0000917 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000918
919 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000920 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000921
922 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
923 TypeAHasClassB,
Daniel Jaspera7564432012-09-13 13:11:25 +0000924 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000925
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000926 StatementMatcher MethodX =
927 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek4da21662012-07-06 05:48:52 +0000928
929 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
930 MethodX,
Daniel Jaspera7564432012-09-13 13:11:25 +0000931 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000932}
933
934TEST(Matcher, BindTheSameNameInAlternatives) {
935 StatementMatcher matcher = anyOf(
936 binaryOperator(hasOperatorName("+"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000937 hasLHS(expr().bind("x")),
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000938 hasRHS(integerLiteral(equals(0)))),
939 binaryOperator(hasOperatorName("+"),
940 hasLHS(integerLiteral(equals(0))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000941 hasRHS(expr().bind("x"))));
Daniel Jaspere0e6b9e2012-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 Jaspera7564432012-09-13 13:11:25 +0000948 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000949}
950
Manuel Klimek66341c52012-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 Jaspera7564432012-09-13 13:11:25 +0000960 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimek66341c52012-08-30 19:41:06 +0000961}
962
Daniel Jasper189f2e42012-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 Vaneb45083d2013-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 Vane52380602013-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 Vane3abf7782013-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 Klimek4da21662012-07-06 05:48:52 +0000989TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000990 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000991 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000992 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000993 EXPECT_TRUE(
994 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000995 expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000996 EXPECT_TRUE(
997 matches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000998 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000999}
1000
1001TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001002 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek4da21662012-07-06 05:48:52 +00001003 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001004 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001005 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001006 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001007 EXPECT_TRUE(
1008 matches("class X {}; void y() { X *x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001009 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001010}
1011
1012TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001013 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +00001014 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001015 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001016 EXPECT_TRUE(
1017 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001018 expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001019}
1020
1021TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001022 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +00001023 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001024 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001025 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001026 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001027}
1028
Manuel Klimek1a68afd2013-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 Klimek4da21662012-07-06 05:48:52 +00001038TEST(Matcher, Call) {
1039 // FIXME: Do we want to overload Call() to directly take
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001040 // Matcher<Decl>, too?
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001041 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +00001046 StatementMatcher MethodOnY =
1047 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +00001066 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek4da21662012-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 Jasper31f7c082012-10-01 13:40:41 +00001085TEST(Matcher, Lambda) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001086 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper31f7c082012-10-01 13:40:41 +00001087 lambdaExpr()));
1088}
1089
1090TEST(Matcher, ForRange) {
Daniel Jasper1a00fee2012-10-01 15:05:34 +00001091 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1092 "void f() { for (auto &a : as); }",
Daniel Jasper31f7c082012-10-01 13:40:41 +00001093 forRangeStmt()));
1094 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1095 forRangeStmt()));
1096}
1097
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001098TEST(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 Jasper31f7c082012-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 Jasperb54b7642012-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 Jaspere0e6b9e2012-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 Jasper2dc75ed2012-08-24 05:12:34 +00001129 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001130 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001131 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001132 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001133 fieldDecl(hasType(asString("ns::A")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001134 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
Stephen Hines651f13c2014-04-23 16:59:28 -07001135 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001136}
1137
Manuel Klimek4da21662012-07-06 05:48:52 +00001138TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001139 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +00001166 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +00001171 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek4da21662012-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));
Stephen Hines176edba2014-12-01 14:53:08 -08001176 StatementMatcher OpStarCall =
1177 operatorCallExpr(hasOverloadedOperatorName("*"));
1178 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1179 OpStarCall));
Edwin Vane6a19a972013-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)) ;
Stephen Hines176edba2014-12-01 14:53:08 -08001186 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1187 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1188 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek4da21662012-07-06 05:48:52 +00001189}
1190
Daniel Jasper278057f2012-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 Klimek4da21662012-07-06 05:48:52 +00001210TEST(Matcher, ThisPointerType) {
Manuel Klimek9f174082012-07-24 13:37:29 +00001211 StatementMatcher MethodOnY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001212 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek4da21662012-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 Jasper2dc75ed2012-08-24 05:12:34 +00001242 declRefExpr(to(
1243 varDecl(hasInitializer(
1244 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek4da21662012-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
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001266TEST(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 Klimek8cb9bf52012-12-04 14:42:08 +00001278TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper9bd28092012-07-30 05:03:25 +00001279 EXPECT_TRUE(matches(
1280 "void f(int i) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001281 varDecl(hasName("i"))));
Daniel Jasper9bd28092012-07-30 05:03:25 +00001282}
1283
Manuel Klimek4da21662012-07-06 05:48:52 +00001284TEST(Matcher, CalledVariable) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001285 StatementMatcher CallOnVariableY =
1286 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-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 Jaspere0e6b9e2012-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 Jasper2dc75ed2012-08-24 05:12:34 +00001323 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001324 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001325 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001326}
1327
Manuel Klimek4da21662012-07-06 05:48:52 +00001328TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001329 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001330}
1331
1332TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001333 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001334}
1335
1336TEST(MemberExpression, MatchesVariable) {
1337 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001338 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001339 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001340 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001341 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001342 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001343}
1344
1345TEST(MemberExpression, MatchesStaticVariable) {
1346 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001347 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001348 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001349 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001350 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001351 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001352}
1353
Daniel Jasper6a124492012-07-12 08:50:38 +00001354TEST(IsInteger, MatchesIntegers) {
Daniel Jasper2dc75ed2012-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 Jasper6a124492012-07-12 08:50:38 +00001360}
1361
1362TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001363 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00001364 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001365 callExpr(hasArgument(0, declRefExpr(
1366 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper6a124492012-07-12 08:50:38 +00001367}
1368
Manuel Klimek4da21662012-07-06 05:48:52 +00001369TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1370 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001371 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001372 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001373 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001374 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001375 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001376}
1377
1378TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1379 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001380 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001381 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001382 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001383 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001384 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001385}
1386
1387TEST(IsArrow, MatchesMemberCallsViaArrow) {
1388 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001389 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001390 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001391 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001392 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001393 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001394}
1395
1396TEST(Callee, MatchesDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001397 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001398
1399 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1400 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1401}
1402
1403TEST(Callee, MatchesMemberExpressions) {
1404 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001405 callExpr(callee(memberExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001406 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001407 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001408}
1409
1410TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001411 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001412
1413 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1414 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1415
Stephen Hines651f13c2014-04-23 16:59:28 -07001416 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1417 llvm::Triple::Win32) {
1418 // FIXME: Make this work for MSVC.
1419 // Dependent contexts, but a non-dependent call.
1420 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1421 CallFunctionF));
1422 EXPECT_TRUE(
1423 matches("void f(); template <int N> struct S { void g() { f(); } };",
1424 CallFunctionF));
1425 }
Manuel Klimek4da21662012-07-06 05:48:52 +00001426
1427 // Depedent calls don't match.
1428 EXPECT_TRUE(
1429 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1430 CallFunctionF));
1431 EXPECT_TRUE(
1432 notMatches("void f(int);"
1433 "template <typename T> struct S { void g(T t) { f(t); } };",
1434 CallFunctionF));
1435}
1436
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001437TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1438 EXPECT_TRUE(
1439 matches("template <typename T> void f(T t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001440 functionTemplateDecl(hasName("f"))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001441}
1442
1443TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1444 EXPECT_TRUE(
1445 notMatches("void f(double d); void f(int t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001446 functionTemplateDecl(hasName("f"))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001447}
1448
1449TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1450 EXPECT_TRUE(
1451 notMatches("void g(); template <typename T> void f(T t) {}"
1452 "template <> void f(int t) { g(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001453 functionTemplateDecl(hasName("f"),
1454 hasDescendant(declRefExpr(to(
1455 functionDecl(hasName("g"))))))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001456}
1457
Manuel Klimek4da21662012-07-06 05:48:52 +00001458TEST(Matcher, Argument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001459 StatementMatcher CallArgumentY = callExpr(
1460 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001461
1462 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1463 EXPECT_TRUE(
1464 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1465 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1466
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001467 StatementMatcher WrongIndex = callExpr(
1468 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001469 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1470}
1471
1472TEST(Matcher, AnyArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001473 StatementMatcher CallArgumentY = callExpr(
1474 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001475 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1476 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1477 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1478}
1479
1480TEST(Matcher, ArgumentCount) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001481 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00001482
1483 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1484 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1485 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1486}
1487
Daniel Jasper36e29d62012-12-04 11:54:27 +00001488TEST(Matcher, ParameterCount) {
1489 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1490 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1491 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1492 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1493 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1494}
1495
Manuel Klimek4da21662012-07-06 05:48:52 +00001496TEST(Matcher, References) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001497 DeclarationMatcher ReferenceClassX = varDecl(
1498 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001499 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1500 ReferenceClassX));
1501 EXPECT_TRUE(
1502 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Han4b6730d2013-09-11 15:53:29 +00001503 // The match here is on the implicit copy constructor code for
1504 // class X, not on code 'X x = y'.
Manuel Klimek4da21662012-07-06 05:48:52 +00001505 EXPECT_TRUE(
Michael Han4b6730d2013-09-11 15:53:29 +00001506 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1507 EXPECT_TRUE(
1508 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek4da21662012-07-06 05:48:52 +00001509 EXPECT_TRUE(
1510 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1511}
1512
Edwin Vane6a19a972013-03-06 17:02:57 +00001513TEST(QualType, hasCanonicalType) {
1514 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1515 "int a;"
1516 "int_ref b = a;",
1517 varDecl(hasType(qualType(referenceType())))));
1518 EXPECT_TRUE(
1519 matches("typedef int &int_ref;"
1520 "int a;"
1521 "int_ref b = a;",
1522 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1523}
1524
Edwin Vane7b69cd02013-04-02 18:15:55 +00001525TEST(QualType, hasLocalQualifiers) {
1526 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1527 varDecl(hasType(hasLocalQualifiers()))));
1528 EXPECT_TRUE(matches("int *const j = nullptr;",
1529 varDecl(hasType(hasLocalQualifiers()))));
1530 EXPECT_TRUE(matches("int *volatile k;",
1531 varDecl(hasType(hasLocalQualifiers()))));
1532 EXPECT_TRUE(notMatches("int m;",
1533 varDecl(hasType(hasLocalQualifiers()))));
1534}
1535
Manuel Klimek4da21662012-07-06 05:48:52 +00001536TEST(HasParameter, CallsInnerMatcher) {
1537 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001538 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001539 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001540 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001541}
1542
1543TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1544 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001545 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001546}
1547
1548TEST(HasType, MatchesParameterVariableTypesStrictly) {
1549 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001550 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001551 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001552 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001553 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001554 methodDecl(hasParameter(0,
1555 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001556 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001557 methodDecl(hasParameter(0,
1558 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001559}
1560
1561TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1562 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001563 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001564 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001565 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001566}
1567
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001568TEST(Returns, MatchesReturnTypes) {
1569 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001570 functionDecl(returns(asString("int")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001571 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001572 functionDecl(returns(asString("float")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001573 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001574 functionDecl(returns(hasDeclaration(
1575 recordDecl(hasName("Y")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001576}
1577
Daniel Jasper8cc7efa2012-08-15 18:52:19 +00001578TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001579 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1580 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1581 functionDecl(isExternC())));
1582 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasper8cc7efa2012-08-15 18:52:19 +00001583}
1584
Stephen Hines176edba2014-12-01 14:53:08 -08001585TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1586 EXPECT_TRUE(
1587 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1588 EXPECT_TRUE(matches("void Func() = delete;",
1589 functionDecl(hasName("Func"), isDeleted())));
1590}
1591
Manuel Klimek4da21662012-07-06 05:48:52 +00001592TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1593 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001594 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001595}
1596
1597TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1598 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001599 methodDecl(hasAnyParameter(hasType(pointsTo(
1600 recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001601}
1602
Stephen Hines651f13c2014-04-23 16:59:28 -07001603TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek4da21662012-07-06 05:48:52 +00001604 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001605 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001606 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001607 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001608}
1609
Daniel Jasper371f9392012-08-01 08:40:24 +00001610TEST(Matcher, MatchesClassTemplateSpecialization) {
1611 EXPECT_TRUE(matches("template<typename T> struct A {};"
1612 "template<> struct A<int> {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001613 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001614 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001615 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001616 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001617 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001618}
1619
Manuel Klimek1a68afd2013-06-20 13:08:29 +00001620TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1621 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1622 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1623}
1624
1625TEST(ParmVarDecl, MatchesParmVars) {
1626 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1627 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1628}
1629
Daniel Jasper371f9392012-08-01 08:40:24 +00001630TEST(Matcher, MatchesTypeTemplateArgument) {
1631 EXPECT_TRUE(matches(
1632 "template<typename T> struct B {};"
1633 "B<int> b;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001634 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper371f9392012-08-01 08:40:24 +00001635 asString("int"))))));
1636}
1637
1638TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1639 EXPECT_TRUE(matches(
1640 "struct B { int next; };"
1641 "template<int(B::*next_ptr)> struct A {};"
1642 "A<&B::next> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001643 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1644 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasperaaa8e452012-09-29 15:55:18 +00001645
1646 EXPECT_TRUE(notMatches(
1647 "template <typename T> struct A {};"
1648 "A<int> a;",
1649 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1650 refersToDeclaration(decl())))));
Stephen Hines651f13c2014-04-23 16:59:28 -07001651
1652 EXPECT_TRUE(matches(
1653 "struct B { int next; };"
1654 "template<int(B::*next_ptr)> struct A {};"
1655 "A<&B::next> a;",
1656 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1657 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1658
1659 EXPECT_TRUE(notMatches(
1660 "template <typename T> struct A {};"
1661 "A<int> a;",
1662 templateSpecializationType(hasAnyTemplateArgument(
1663 refersToDeclaration(decl())))));
Daniel Jasper371f9392012-08-01 08:40:24 +00001664}
1665
1666TEST(Matcher, MatchesSpecificArgument) {
1667 EXPECT_TRUE(matches(
1668 "template<typename T, typename U> class A {};"
1669 "A<bool, int> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001670 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper371f9392012-08-01 08:40:24 +00001671 1, refersToType(asString("int"))))));
1672 EXPECT_TRUE(notMatches(
1673 "template<typename T, typename U> class A {};"
1674 "A<int, bool> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001675 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper371f9392012-08-01 08:40:24 +00001676 1, refersToType(asString("int"))))));
Stephen Hines651f13c2014-04-23 16:59:28 -07001677
1678 EXPECT_TRUE(matches(
1679 "template<typename T, typename U> class A {};"
1680 "A<bool, int> a;",
1681 templateSpecializationType(hasTemplateArgument(
1682 1, refersToType(asString("int"))))));
1683 EXPECT_TRUE(notMatches(
1684 "template<typename T, typename U> class A {};"
1685 "A<int, bool> a;",
1686 templateSpecializationType(hasTemplateArgument(
1687 1, refersToType(asString("int"))))));
Daniel Jasper371f9392012-08-01 08:40:24 +00001688}
1689
Stephen Hines176edba2014-12-01 14:53:08 -08001690TEST(TemplateArgument, Matches) {
1691 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1692 classTemplateSpecializationDecl(
1693 hasAnyTemplateArgument(templateArgument()))));
1694 EXPECT_TRUE(matches(
1695 "template<typename T> struct C {}; C<int> c;",
1696 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1697}
1698
1699TEST(TemplateArgumentCountIs, Matches) {
1700 EXPECT_TRUE(
1701 matches("template<typename T> struct C {}; C<int> c;",
1702 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1703 EXPECT_TRUE(
1704 notMatches("template<typename T> struct C {}; C<int> c;",
1705 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1706
1707 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1708 templateSpecializationType(templateArgumentCountIs(1))));
1709 EXPECT_TRUE(
1710 notMatches("template<typename T> struct C {}; C<int> c;",
1711 templateSpecializationType(templateArgumentCountIs(2))));
1712}
1713
1714TEST(IsIntegral, Matches) {
1715 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1716 classTemplateSpecializationDecl(
1717 hasAnyTemplateArgument(isIntegral()))));
1718 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1719 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1720 templateArgument(isIntegral())))));
1721}
1722
1723TEST(RefersToIntegralType, Matches) {
1724 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1725 classTemplateSpecializationDecl(
1726 hasAnyTemplateArgument(refersToIntegralType(
1727 asString("int"))))));
1728 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1729 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1730 refersToIntegralType(asString("int"))))));
1731}
1732
1733TEST(EqualsIntegralValue, Matches) {
1734 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1735 classTemplateSpecializationDecl(
1736 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1737 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1738 classTemplateSpecializationDecl(
1739 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1740 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1741 classTemplateSpecializationDecl(
1742 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1743 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1744 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1745 equalsIntegralValue("0042")))));
1746}
1747
Daniel Jasperf3197e92013-02-25 12:02:08 +00001748TEST(Matcher, MatchesAccessSpecDecls) {
1749 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1750 EXPECT_TRUE(
1751 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1752 EXPECT_TRUE(
1753 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1754 EXPECT_TRUE(
1755 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1756
1757 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1758}
1759
Edwin Vane5771a2f2013-04-09 20:46:36 +00001760TEST(Matcher, MatchesVirtualMethod) {
1761 EXPECT_TRUE(matches("class X { virtual int f(); };",
1762 methodDecl(isVirtual(), hasName("::X::f"))));
1763 EXPECT_TRUE(notMatches("class X { int f(); };",
1764 methodDecl(isVirtual())));
1765}
1766
Stephen Hines651f13c2014-04-23 16:59:28 -07001767TEST(Matcher, MatchesPureMethod) {
1768 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1769 methodDecl(isPure(), hasName("::X::f"))));
1770 EXPECT_TRUE(notMatches("class X { int f(); };",
1771 methodDecl(isPure())));
1772}
1773
Edwin Vane32a6ebc2013-05-09 17:00:17 +00001774TEST(Matcher, MatchesConstMethod) {
1775 EXPECT_TRUE(matches("struct A { void foo() const; };",
1776 methodDecl(isConst())));
1777 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1778 methodDecl(isConst())));
1779}
1780
Edwin Vane5771a2f2013-04-09 20:46:36 +00001781TEST(Matcher, MatchesOverridingMethod) {
1782 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1783 "class Y : public X { int f(); };",
1784 methodDecl(isOverride(), hasName("::Y::f"))));
1785 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1786 "class Y : public X { int f(); };",
1787 methodDecl(isOverride(), hasName("::X::f"))));
1788 EXPECT_TRUE(notMatches("class X { int f(); }; "
1789 "class Y : public X { int f(); };",
1790 methodDecl(isOverride())));
1791 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1792 methodDecl(isOverride())));
1793}
1794
Manuel Klimek4da21662012-07-06 05:48:52 +00001795TEST(Matcher, ConstructorCall) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001796 StatementMatcher Constructor = constructExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001797
1798 EXPECT_TRUE(
1799 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1800 EXPECT_TRUE(
1801 matches("class X { public: X(); }; void x() { X x = X(); }",
1802 Constructor));
1803 EXPECT_TRUE(
1804 matches("class X { public: X(int); }; void x() { X x = 0; }",
1805 Constructor));
1806 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1807}
1808
1809TEST(Matcher, ConstructorArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001810 StatementMatcher Constructor = constructExpr(
1811 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001812
1813 EXPECT_TRUE(
1814 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1815 Constructor));
1816 EXPECT_TRUE(
1817 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1818 Constructor));
1819 EXPECT_TRUE(
1820 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1821 Constructor));
1822 EXPECT_TRUE(
1823 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1824 Constructor));
1825
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001826 StatementMatcher WrongIndex = constructExpr(
1827 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001828 EXPECT_TRUE(
1829 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1830 WrongIndex));
1831}
1832
1833TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001834 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00001835
1836 EXPECT_TRUE(
1837 matches("class X { public: X(int); }; void x() { X x(0); }",
1838 Constructor1Arg));
1839 EXPECT_TRUE(
1840 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1841 Constructor1Arg));
1842 EXPECT_TRUE(
1843 matches("class X { public: X(int); }; void x() { X x = 0; }",
1844 Constructor1Arg));
1845 EXPECT_TRUE(
1846 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1847 Constructor1Arg));
1848}
1849
Stephen Hines651f13c2014-04-23 16:59:28 -07001850TEST(Matcher, ConstructorListInitialization) {
1851 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1852
1853 EXPECT_TRUE(
1854 matches("class X { public: X(int); }; void x() { X x{0}; }",
1855 ConstructorListInit));
1856 EXPECT_FALSE(
1857 matches("class X { public: X(int); }; void x() { X x(0); }",
1858 ConstructorListInit));
1859}
1860
Manuel Klimek70b9db92012-10-23 10:40:50 +00001861TEST(Matcher,ThisExpr) {
1862 EXPECT_TRUE(
1863 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1864 EXPECT_TRUE(
1865 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1866}
1867
Manuel Klimek4da21662012-07-06 05:48:52 +00001868TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001869 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001870
1871 std::string ClassString = "class string { public: string(); ~string(); }; ";
1872
1873 EXPECT_TRUE(
1874 matches(ClassString +
1875 "string GetStringByValue();"
1876 "void FunctionTakesString(string s);"
1877 "void run() { FunctionTakesString(GetStringByValue()); }",
1878 TempExpression));
1879
1880 EXPECT_TRUE(
1881 notMatches(ClassString +
1882 "string* GetStringPointer(); "
1883 "void FunctionTakesStringPtr(string* s);"
1884 "void run() {"
1885 " string* s = GetStringPointer();"
1886 " FunctionTakesStringPtr(GetStringPointer());"
1887 " FunctionTakesStringPtr(s);"
1888 "}",
1889 TempExpression));
1890
1891 EXPECT_TRUE(
1892 notMatches("class no_dtor {};"
1893 "no_dtor GetObjByValue();"
1894 "void ConsumeObj(no_dtor param);"
1895 "void run() { ConsumeObj(GetObjByValue()); }",
1896 TempExpression));
1897}
1898
Sam Panzere16acd32012-08-24 22:04:44 +00001899TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1900 std::string ClassString =
1901 "class string { public: string(); int length(); }; ";
1902
1903 EXPECT_TRUE(
1904 matches(ClassString +
1905 "string GetStringByValue();"
1906 "void FunctionTakesString(string s);"
1907 "void run() { FunctionTakesString(GetStringByValue()); }",
1908 materializeTemporaryExpr()));
1909
1910 EXPECT_TRUE(
1911 notMatches(ClassString +
1912 "string* GetStringPointer(); "
1913 "void FunctionTakesStringPtr(string* s);"
1914 "void run() {"
1915 " string* s = GetStringPointer();"
1916 " FunctionTakesStringPtr(GetStringPointer());"
1917 " FunctionTakesStringPtr(s);"
1918 "}",
1919 materializeTemporaryExpr()));
1920
1921 EXPECT_TRUE(
1922 notMatches(ClassString +
1923 "string GetStringByValue();"
1924 "void run() { int k = GetStringByValue().length(); }",
1925 materializeTemporaryExpr()));
1926
1927 EXPECT_TRUE(
1928 notMatches(ClassString +
1929 "string GetStringByValue();"
1930 "void run() { GetStringByValue(); }",
1931 materializeTemporaryExpr()));
1932}
1933
Manuel Klimek4da21662012-07-06 05:48:52 +00001934TEST(ConstructorDeclaration, SimpleCase) {
1935 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001936 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001937 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001938 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001939}
1940
1941TEST(ConstructorDeclaration, IsImplicit) {
1942 // This one doesn't match because the constructor is not added by the
1943 // compiler (it is not needed).
1944 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001945 constructorDecl(isImplicit())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001946 // The compiler added the implicit default constructor.
1947 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001948 constructorDecl(isImplicit())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001949 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001950 constructorDecl(unless(isImplicit()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001951 // The compiler added an implicit assignment operator.
1952 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1953 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001954}
1955
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001956TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1957 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001958 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001959}
1960
1961TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001962 EXPECT_TRUE(notMatches("class Foo {};",
1963 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001964}
1965
Manuel Klimek4da21662012-07-06 05:48:52 +00001966TEST(HasAnyConstructorInitializer, SimpleCase) {
1967 EXPECT_TRUE(notMatches(
1968 "class Foo { Foo() { } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001969 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001970 EXPECT_TRUE(matches(
1971 "class Foo {"
1972 " Foo() : foo_() { }"
1973 " int foo_;"
1974 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001975 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001976}
1977
1978TEST(HasAnyConstructorInitializer, ForField) {
1979 static const char Code[] =
1980 "class Baz { };"
1981 "class Foo {"
1982 " Foo() : foo_() { }"
1983 " Baz foo_;"
1984 " Baz bar_;"
1985 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001986 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1987 forField(hasType(recordDecl(hasName("Baz"))))))));
1988 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001989 forField(hasName("foo_"))))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001990 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1991 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001992}
1993
1994TEST(HasAnyConstructorInitializer, WithInitializer) {
1995 static const char Code[] =
1996 "class Foo {"
1997 " Foo() : foo_(0) { }"
1998 " int foo_;"
1999 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002000 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00002001 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002002 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00002003 withInitializer(integerLiteral(equals(1)))))));
2004}
2005
2006TEST(HasAnyConstructorInitializer, IsWritten) {
2007 static const char Code[] =
2008 "struct Bar { Bar(){} };"
2009 "class Foo {"
2010 " Foo() : foo_() { }"
2011 " Bar foo_;"
2012 " Bar bar_;"
2013 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002014 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00002015 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002016 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00002017 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002018 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00002019 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2020}
2021
2022TEST(Matcher, NewExpression) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002023 StatementMatcher New = newExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00002024
2025 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2026 EXPECT_TRUE(
2027 matches("class X { public: X(); }; void x() { new X(); }", New));
2028 EXPECT_TRUE(
2029 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2030 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2031}
2032
2033TEST(Matcher, NewExpressionArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002034 StatementMatcher New = constructExpr(
2035 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002036
2037 EXPECT_TRUE(
2038 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2039 New));
2040 EXPECT_TRUE(
2041 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2042 New));
2043 EXPECT_TRUE(
2044 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2045 New));
2046
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002047 StatementMatcher WrongIndex = constructExpr(
2048 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002049 EXPECT_TRUE(
2050 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2051 WrongIndex));
2052}
2053
2054TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002055 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00002056
2057 EXPECT_TRUE(
2058 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2059 EXPECT_TRUE(
2060 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2061 New));
2062}
2063
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002064TEST(Matcher, DeleteExpression) {
2065 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002066 deleteExpr()));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002067}
2068
Manuel Klimek4da21662012-07-06 05:48:52 +00002069TEST(Matcher, DefaultArgument) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002070 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00002071
2072 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2073 EXPECT_TRUE(
2074 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2075 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2076}
2077
2078TEST(Matcher, StringLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002079 StatementMatcher Literal = stringLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00002080 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2081 // wide string
2082 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2083 // with escaped characters
2084 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2085 // no matching -- though the data type is the same, there is no string literal
2086 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2087}
2088
2089TEST(Matcher, CharacterLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002090 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00002091 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2092 // wide character
2093 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2094 // wide character, Hex encoded, NOT MATCHED!
2095 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2096 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2097}
2098
2099TEST(Matcher, IntegerLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002100 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00002101 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2102 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2103 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2104 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2105
2106 // Non-matching cases (character literals, float and double)
2107 EXPECT_TRUE(notMatches("int i = L'a';",
2108 HasIntLiteral)); // this is actually a character
2109 // literal cast to int
2110 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2111 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2112 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2113}
2114
Daniel Jasperc5ae7172013-07-26 18:52:58 +00002115TEST(Matcher, FloatLiterals) {
2116 StatementMatcher HasFloatLiteral = floatLiteral();
2117 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2118 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2119 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2120 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2121 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002122 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2123 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2124 EXPECT_TRUE(
2125 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasperc5ae7172013-07-26 18:52:58 +00002126
2127 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002128 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2129 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2130 EXPECT_TRUE(
2131 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasperc5ae7172013-07-26 18:52:58 +00002132}
2133
Daniel Jasper31f7c082012-10-01 13:40:41 +00002134TEST(Matcher, NullPtrLiteral) {
2135 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2136}
2137
Daniel Jasperb54b7642012-09-20 14:12:57 +00002138TEST(Matcher, AsmStatement) {
2139 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2140}
2141
Manuel Klimek4da21662012-07-06 05:48:52 +00002142TEST(Matcher, Conditions) {
2143 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2144
2145 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2146 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2147 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2148 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2149 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2150}
2151
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002152TEST(IfStmt, ChildTraversalMatchers) {
2153 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2154 ifStmt(hasThen(boolLiteral(equals(true))))));
2155 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2156 ifStmt(hasThen(boolLiteral(equals(true))))));
2157 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2158 ifStmt(hasElse(boolLiteral(equals(true))))));
2159 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2160 ifStmt(hasElse(boolLiteral(equals(true))))));
2161}
2162
Manuel Klimek4da21662012-07-06 05:48:52 +00002163TEST(MatchBinaryOperator, HasOperatorName) {
2164 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2165
2166 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2167 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2168}
2169
2170TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2171 StatementMatcher OperatorTrueFalse =
2172 binaryOperator(hasLHS(boolLiteral(equals(true))),
2173 hasRHS(boolLiteral(equals(false))));
2174
2175 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2176 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2177 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2178}
2179
2180TEST(MatchBinaryOperator, HasEitherOperand) {
2181 StatementMatcher HasOperand =
2182 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2183
2184 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2185 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2186 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2187}
2188
2189TEST(Matcher, BinaryOperatorTypes) {
2190 // Integration test that verifies the AST provides all binary operators in
2191 // a way we expect.
2192 // FIXME: Operator ','
2193 EXPECT_TRUE(
2194 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2195 EXPECT_TRUE(
2196 matches("bool b; bool c = (b = true);",
2197 binaryOperator(hasOperatorName("="))));
2198 EXPECT_TRUE(
2199 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2200 EXPECT_TRUE(
2201 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2202 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2203 EXPECT_TRUE(
2204 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2205 EXPECT_TRUE(
2206 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2207 EXPECT_TRUE(
2208 matches("int i = 1; int j = (i <<= 2);",
2209 binaryOperator(hasOperatorName("<<="))));
2210 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2211 EXPECT_TRUE(
2212 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2213 EXPECT_TRUE(
2214 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2215 EXPECT_TRUE(
2216 matches("int i = 1; int j = (i >>= 2);",
2217 binaryOperator(hasOperatorName(">>="))));
2218 EXPECT_TRUE(
2219 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2220 EXPECT_TRUE(
2221 matches("int i = 42; int j = (i ^= 42);",
2222 binaryOperator(hasOperatorName("^="))));
2223 EXPECT_TRUE(
2224 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2225 EXPECT_TRUE(
2226 matches("int i = 42; int j = (i %= 42);",
2227 binaryOperator(hasOperatorName("%="))));
2228 EXPECT_TRUE(
2229 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2230 EXPECT_TRUE(
2231 matches("bool b = true && false;",
2232 binaryOperator(hasOperatorName("&&"))));
2233 EXPECT_TRUE(
2234 matches("bool b = true; bool c = (b &= false);",
2235 binaryOperator(hasOperatorName("&="))));
2236 EXPECT_TRUE(
2237 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2238 EXPECT_TRUE(
2239 matches("bool b = true || false;",
2240 binaryOperator(hasOperatorName("||"))));
2241 EXPECT_TRUE(
2242 matches("bool b = true; bool c = (b |= false);",
2243 binaryOperator(hasOperatorName("|="))));
2244 EXPECT_TRUE(
2245 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2246 EXPECT_TRUE(
2247 matches("int i = 42; int j = (i *= 23);",
2248 binaryOperator(hasOperatorName("*="))));
2249 EXPECT_TRUE(
2250 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2251 EXPECT_TRUE(
2252 matches("int i = 42; int j = (i /= 23);",
2253 binaryOperator(hasOperatorName("/="))));
2254 EXPECT_TRUE(
2255 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2256 EXPECT_TRUE(
2257 matches("int i = 42; int j = (i += 23);",
2258 binaryOperator(hasOperatorName("+="))));
2259 EXPECT_TRUE(
2260 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2261 EXPECT_TRUE(
2262 matches("int i = 42; int j = (i -= 23);",
2263 binaryOperator(hasOperatorName("-="))));
2264 EXPECT_TRUE(
2265 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2266 binaryOperator(hasOperatorName("->*"))));
2267 EXPECT_TRUE(
2268 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2269 binaryOperator(hasOperatorName(".*"))));
2270
2271 // Member expressions as operators are not supported in matches.
2272 EXPECT_TRUE(
2273 notMatches("struct A { void x(A *a) { a->x(this); } };",
2274 binaryOperator(hasOperatorName("->"))));
2275
2276 // Initializer assignments are not represented as operator equals.
2277 EXPECT_TRUE(
2278 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2279
2280 // Array indexing is not represented as operator.
2281 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2282
2283 // Overloaded operators do not match at all.
2284 EXPECT_TRUE(notMatches(
2285 "struct A { bool operator&&(const A &a) const { return false; } };"
2286 "void x() { A a, b; a && b; }",
2287 binaryOperator()));
2288}
2289
2290TEST(MatchUnaryOperator, HasOperatorName) {
2291 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2292
2293 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2294 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2295}
2296
2297TEST(MatchUnaryOperator, HasUnaryOperand) {
2298 StatementMatcher OperatorOnFalse =
2299 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2300
2301 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2302 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2303}
2304
2305TEST(Matcher, UnaryOperatorTypes) {
2306 // Integration test that verifies the AST provides all unary operators in
2307 // a way we expect.
2308 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2309 EXPECT_TRUE(
2310 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2311 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2312 EXPECT_TRUE(
2313 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2314 EXPECT_TRUE(
2315 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2316 EXPECT_TRUE(
2317 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2318 EXPECT_TRUE(
2319 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2320 EXPECT_TRUE(
2321 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2322 EXPECT_TRUE(
2323 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2324 EXPECT_TRUE(
2325 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2326
2327 // We don't match conversion operators.
2328 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2329
2330 // Function calls are not represented as operator.
2331 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2332
2333 // Overloaded operators do not match at all.
2334 // FIXME: We probably want to add that.
2335 EXPECT_TRUE(notMatches(
2336 "struct A { bool operator!() const { return false; } };"
2337 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2338}
2339
2340TEST(Matcher, ConditionalOperator) {
2341 StatementMatcher Conditional = conditionalOperator(
2342 hasCondition(boolLiteral(equals(true))),
2343 hasTrueExpression(boolLiteral(equals(false))));
2344
2345 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2346 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2347 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2348
2349 StatementMatcher ConditionalFalse = conditionalOperator(
2350 hasFalseExpression(boolLiteral(equals(false))));
2351
2352 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2353 EXPECT_TRUE(
2354 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2355}
2356
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002357TEST(ArraySubscriptMatchers, ArraySubscripts) {
2358 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2359 arraySubscriptExpr()));
2360 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2361 arraySubscriptExpr()));
2362}
2363
2364TEST(ArraySubscriptMatchers, ArrayIndex) {
2365 EXPECT_TRUE(matches(
2366 "int i[2]; void f() { i[1] = 1; }",
2367 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2368 EXPECT_TRUE(matches(
2369 "int i[2]; void f() { 1[i] = 1; }",
2370 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2371 EXPECT_TRUE(notMatches(
2372 "int i[2]; void f() { i[1] = 1; }",
2373 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2374}
2375
2376TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2377 EXPECT_TRUE(matches(
2378 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002379 arraySubscriptExpr(hasBase(implicitCastExpr(
2380 hasSourceExpression(declRefExpr()))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002381}
2382
Manuel Klimek4da21662012-07-06 05:48:52 +00002383TEST(Matcher, HasNameSupportsNamespaces) {
2384 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002385 recordDecl(hasName("a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002386 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002387 recordDecl(hasName("::a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002388 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002389 recordDecl(hasName("b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002390 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002391 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002392 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002393 recordDecl(hasName("c::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002394 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002395 recordDecl(hasName("a::c::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002396 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002397 recordDecl(hasName("a::b::A"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002398 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002399 recordDecl(hasName("::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002400 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002401 recordDecl(hasName("::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002402 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002403 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002404 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002405 recordDecl(hasName("a+b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002406 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002407 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002408}
2409
2410TEST(Matcher, HasNameSupportsOuterClasses) {
2411 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002412 matches("class A { class B { class C; }; };",
2413 recordDecl(hasName("A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002414 EXPECT_TRUE(
2415 matches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002416 recordDecl(hasName("::A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002417 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002418 matches("class A { class B { class C; }; };",
2419 recordDecl(hasName("B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002420 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002421 matches("class A { class B { class C; }; };",
2422 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002423 EXPECT_TRUE(
2424 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002425 recordDecl(hasName("c::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002426 EXPECT_TRUE(
2427 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002428 recordDecl(hasName("A::c::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002429 EXPECT_TRUE(
2430 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002431 recordDecl(hasName("A::B::A"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002432 EXPECT_TRUE(
2433 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002434 recordDecl(hasName("::C"))));
2435 EXPECT_TRUE(
2436 notMatches("class A { class B { class C; }; };",
2437 recordDecl(hasName("::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002438 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002439 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002440 EXPECT_TRUE(
2441 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002442 recordDecl(hasName("A+B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002443}
2444
2445TEST(Matcher, IsDefinition) {
2446 DeclarationMatcher DefinitionOfClassA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002447 recordDecl(hasName("A"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002448 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2449 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2450
2451 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002452 varDecl(hasName("a"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002453 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2454 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2455
2456 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002457 methodDecl(hasName("a"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002458 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2459 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2460}
2461
2462TEST(Matcher, OfClass) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002463 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +00002464 ofClass(hasName("X")))));
2465
2466 EXPECT_TRUE(
2467 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2468 EXPECT_TRUE(
2469 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2470 Constructor));
2471 EXPECT_TRUE(
2472 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2473 Constructor));
2474}
2475
2476TEST(Matcher, VisitsTemplateInstantiations) {
2477 EXPECT_TRUE(matches(
2478 "class A { public: void x(); };"
2479 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002480 "void f() { B<A> b; b.y(); }",
2481 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002482
2483 EXPECT_TRUE(matches(
2484 "class A { public: void x(); };"
2485 "class C {"
2486 " public:"
2487 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2488 "};"
2489 "void f() {"
2490 " C::B<A> b; b.y();"
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002491 "}",
2492 recordDecl(hasName("C"),
2493 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002494}
2495
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002496TEST(Matcher, HandlesNullQualTypes) {
2497 // FIXME: Add a Type matcher so we can replace uses of this
2498 // variable with Type(True())
2499 const TypeMatcher AnyType = anything();
2500
2501 // We don't really care whether this matcher succeeds; we're testing that
2502 // it completes without crashing.
2503 EXPECT_TRUE(matches(
2504 "struct A { };"
2505 "template <typename T>"
2506 "void f(T t) {"
2507 " T local_t(t /* this becomes a null QualType in the AST */);"
2508 "}"
2509 "void g() {"
2510 " f(0);"
2511 "}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002512 expr(hasType(TypeMatcher(
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002513 anyOf(
2514 TypeMatcher(hasDeclaration(anything())),
2515 pointsTo(AnyType),
2516 references(AnyType)
2517 // Other QualType matchers should go here.
2518 ))))));
2519}
2520
Manuel Klimek4da21662012-07-06 05:48:52 +00002521// For testing AST_MATCHER_P().
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002522AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002523 // Make sure all special variables are used: node, match_finder,
2524 // bound_nodes_builder, and the parameter named 'AMatcher'.
2525 return AMatcher.matches(Node, Finder, Builder);
2526}
2527
2528TEST(AstMatcherPMacro, Works) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002529 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002530
2531 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002532 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002533
2534 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002535 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002536
2537 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002538 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002539}
2540
2541AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenef7eb022013-06-21 15:51:31 +00002542 polymorphicHas,
2543 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2544 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002545 return Finder->matchesChildOf(
Manuel Klimeka78d0d62012-09-05 12:12:07 +00002546 Node, AMatcher, Builder,
Manuel Klimek4da21662012-07-06 05:48:52 +00002547 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2548 ASTMatchFinder::BK_First);
2549}
2550
2551TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002552 DeclarationMatcher HasClassB =
2553 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek4da21662012-07-06 05:48:52 +00002554
2555 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002556 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002557
2558 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002559 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002560
2561 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002562 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002563
2564 StatementMatcher StatementHasClassB =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002565 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002566
2567 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2568}
2569
2570TEST(For, FindsForLoops) {
2571 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2572 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper1a00fee2012-10-01 15:05:34 +00002573 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2574 "void f() { for (auto &a : as); }",
Daniel Jasper31f7c082012-10-01 13:40:41 +00002575 forStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002576}
2577
Daniel Jasper6a124492012-07-12 08:50:38 +00002578TEST(For, ForLoopInternals) {
2579 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2580 forStmt(hasCondition(anything()))));
2581 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2582 forStmt(hasLoopInit(anything()))));
2583}
2584
Stephen Hines651f13c2014-04-23 16:59:28 -07002585TEST(For, ForRangeLoopInternals) {
2586 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2587 forRangeStmt(hasLoopVariable(anything()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002588 EXPECT_TRUE(matches(
2589 "void f(){ int a[] {1, 2}; for (int i : a); }",
2590 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Stephen Hines651f13c2014-04-23 16:59:28 -07002591}
2592
Daniel Jasper6a124492012-07-12 08:50:38 +00002593TEST(For, NegativeForLoopInternals) {
2594 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002595 forStmt(hasCondition(expr()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002596 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2597 forStmt(hasLoopInit(anything()))));
2598}
2599
Manuel Klimek4da21662012-07-06 05:48:52 +00002600TEST(For, ReportsNoFalsePositives) {
2601 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2602 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2603}
2604
2605TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002606 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2607 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2608 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002609}
2610
2611TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2612 // It's not a compound statement just because there's "{}" in the source
2613 // text. This is an AST search, not grep.
2614 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002615 compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002616 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002617 compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002618}
2619
Daniel Jasper6a124492012-07-12 08:50:38 +00002620TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002621 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002622 forStmt(hasBody(compoundStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002623 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002624 forStmt(hasBody(compoundStmt()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002625 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002626 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002627 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002628 doStmt(hasBody(compoundStmt()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002629 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2630 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002631}
2632
2633TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2634 // The simplest case: every compound statement is in a function
2635 // definition, and the function body itself must be a compound
2636 // statement.
2637 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002638 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002639}
2640
2641TEST(HasAnySubstatement, IsNotRecursive) {
2642 // It's really "has any immediate substatement".
2643 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002644 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002645}
2646
2647TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2648 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002649 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002650}
2651
2652TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2653 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002654 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002655}
2656
2657TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2658 EXPECT_TRUE(matches("void f() { }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002659 compoundStmt(statementCountIs(0))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002660 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002661 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002662}
2663
2664TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2665 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002666 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002667 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002668 compoundStmt(statementCountIs(0))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002669 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002670 compoundStmt(statementCountIs(2))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002671}
2672
2673TEST(StatementCountIs, WorksWithMultipleStatements) {
2674 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002675 compoundStmt(statementCountIs(3))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002676}
2677
2678TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2679 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002680 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002681 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002682 compoundStmt(statementCountIs(2))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002683 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002684 compoundStmt(statementCountIs(3))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002685 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002686 compoundStmt(statementCountIs(4))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002687}
2688
2689TEST(Member, WorksInSimplestCase) {
2690 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002691 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002692}
2693
2694TEST(Member, DoesNotMatchTheBaseExpression) {
2695 // Don't pick out the wrong part of the member expression, this should
2696 // be checking the member (name) only.
2697 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002698 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002699}
2700
2701TEST(Member, MatchesInMemberFunctionCall) {
2702 EXPECT_TRUE(matches("void f() {"
2703 " struct { void first() {}; } s;"
2704 " s.first();"
2705 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002706 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002707}
2708
Daniel Jasperc711af22012-10-23 15:46:39 +00002709TEST(Member, MatchesMember) {
2710 EXPECT_TRUE(matches(
2711 "struct A { int i; }; void f() { A a; a.i = 2; }",
2712 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2713 EXPECT_TRUE(notMatches(
2714 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2715 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2716}
2717
Daniel Jasperf3197e92013-02-25 12:02:08 +00002718TEST(Member, UnderstandsAccess) {
2719 EXPECT_TRUE(matches(
2720 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2721 EXPECT_TRUE(notMatches(
2722 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2723 EXPECT_TRUE(notMatches(
2724 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2725
2726 EXPECT_TRUE(notMatches(
2727 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2728 EXPECT_TRUE(notMatches(
2729 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2730 EXPECT_TRUE(matches(
2731 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2732
2733 EXPECT_TRUE(notMatches(
2734 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2735 EXPECT_TRUE(matches("class A { protected: int i; };",
2736 fieldDecl(isProtected(), hasName("i"))));
2737 EXPECT_TRUE(notMatches(
2738 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2739
2740 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2741 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2742 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2743 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2744}
2745
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002746TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper31f7c082012-10-01 13:40:41 +00002747 // Fails in C++11 mode
2748 EXPECT_TRUE(matchesConditionally(
2749 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2750 "class X { void *operator new(std::size_t); };",
2751 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002752
2753 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002754 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002755
Daniel Jasper31f7c082012-10-01 13:40:41 +00002756 // Fails in C++11 mode
2757 EXPECT_TRUE(matchesConditionally(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002758 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2759 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper31f7c082012-10-01 13:40:41 +00002760 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002761}
2762
Manuel Klimek4da21662012-07-06 05:48:52 +00002763TEST(HasObjectExpression, DoesNotMatchMember) {
2764 EXPECT_TRUE(notMatches(
2765 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002766 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002767}
2768
2769TEST(HasObjectExpression, MatchesBaseOfVariable) {
2770 EXPECT_TRUE(matches(
2771 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002772 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002773 EXPECT_TRUE(matches(
2774 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002775 memberExpr(hasObjectExpression(
2776 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002777}
2778
2779TEST(HasObjectExpression,
2780 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2781 EXPECT_TRUE(matches(
2782 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002783 memberExpr(hasObjectExpression(
2784 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002785 EXPECT_TRUE(matches(
2786 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002787 memberExpr(hasObjectExpression(
2788 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002789}
2790
2791TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002792 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2793 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2794 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2795 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002796}
2797
2798TEST(Field, MatchesField) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002799 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002800}
2801
2802TEST(IsConstQualified, MatchesConstInt) {
2803 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002804 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002805}
2806
2807TEST(IsConstQualified, MatchesConstPointer) {
2808 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002809 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002810}
2811
2812TEST(IsConstQualified, MatchesThroughTypedef) {
2813 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002814 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002815 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002816 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002817}
2818
2819TEST(IsConstQualified, DoesNotMatchInappropriately) {
2820 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002821 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002822 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002823 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002824}
2825
Sam Panzer089e5b32012-08-16 16:58:10 +00002826TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002827 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2828 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2829 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2830 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002831}
2832TEST(CastExpression, MatchesImplicitCasts) {
2833 // This test creates an implicit cast from int to char.
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002834 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002835 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002836 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002837}
2838
2839TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002840 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2841 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2842 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2843 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002844}
2845
Manuel Klimek4da21662012-07-06 05:48:52 +00002846TEST(ReinterpretCast, MatchesSimpleCase) {
2847 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002848 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002849}
2850
2851TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002852 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002853 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002854 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002855 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002856 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002857 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2858 "B b;"
2859 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002860 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002861}
2862
2863TEST(FunctionalCast, MatchesSimpleCase) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002864 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek4da21662012-07-06 05:48:52 +00002865 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002866 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002867}
2868
2869TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002870 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek4da21662012-07-06 05:48:52 +00002871 EXPECT_TRUE(
2872 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002873 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002874 EXPECT_TRUE(
2875 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002876 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002877}
2878
2879TEST(DynamicCast, MatchesSimpleCase) {
2880 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2881 "B b;"
2882 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002883 dynamicCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002884}
2885
2886TEST(StaticCast, MatchesSimpleCase) {
2887 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002888 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002889}
2890
2891TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002892 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002893 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002894 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002895 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002896 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002897 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2898 "B b;"
2899 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002900 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002901}
2902
Daniel Jaspere6d2a962012-09-18 13:36:17 +00002903TEST(CStyleCast, MatchesSimpleCase) {
2904 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2905}
2906
2907TEST(CStyleCast, DoesNotMatchOtherCasts) {
2908 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2909 "char q, *r = const_cast<char*>(&q);"
2910 "void* s = reinterpret_cast<char*>(&s);"
2911 "struct B { virtual ~B() {} }; struct D : B {};"
2912 "B b;"
2913 "D* t = dynamic_cast<D*>(&b);",
2914 cStyleCastExpr()));
2915}
2916
Manuel Klimek4da21662012-07-06 05:48:52 +00002917TEST(HasDestinationType, MatchesSimpleCase) {
2918 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002919 staticCastExpr(hasDestinationType(
2920 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002921}
2922
Sam Panzer089e5b32012-08-16 16:58:10 +00002923TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2924 // This test creates an implicit const cast.
2925 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002926 implicitCastExpr(
2927 hasImplicitDestinationType(isInteger()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002928 // This test creates an implicit array-to-pointer cast.
2929 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002930 implicitCastExpr(hasImplicitDestinationType(
2931 pointsTo(TypeMatcher(anything()))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002932}
2933
2934TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2935 // This test creates an implicit cast from int to char.
2936 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002937 implicitCastExpr(hasImplicitDestinationType(
2938 unless(anything())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002939 // This test creates an implicit array-to-pointer cast.
2940 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002941 implicitCastExpr(hasImplicitDestinationType(
2942 unless(anything())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002943}
2944
2945TEST(ImplicitCast, MatchesSimpleCase) {
2946 // This test creates an implicit const cast.
2947 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002948 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002949 // This test creates an implicit cast from int to char.
2950 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002951 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002952 // This test creates an implicit array-to-pointer cast.
2953 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002954 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002955}
2956
2957TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002958 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer089e5b32012-08-16 16:58:10 +00002959 // are present, and that it ignores explicit and paren casts.
2960
2961 // These two test cases have no casts.
2962 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002963 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002964 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002965 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002966
2967 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002968 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002969 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002970 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002971
2972 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002973 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002974}
2975
2976TEST(IgnoringImpCasts, MatchesImpCasts) {
2977 // This test checks that ignoringImpCasts matches when implicit casts are
2978 // present and its inner matcher alone does not match.
2979 // Note that this test creates an implicit const cast.
2980 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002981 varDecl(hasInitializer(ignoringImpCasts(
2982 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002983 // This test creates an implict cast from int to char.
2984 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002985 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002986 integerLiteral(equals(0)))))));
2987}
2988
2989TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2990 // These tests verify that ignoringImpCasts does not match if the inner
2991 // matcher does not match.
2992 // Note that the first test creates an implicit const cast.
2993 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002994 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002995 unless(anything()))))));
2996 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002997 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002998 unless(anything()))))));
2999
3000 // These tests verify that ignoringImplictCasts does not look through explicit
3001 // casts or parentheses.
3002 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003003 varDecl(hasInitializer(ignoringImpCasts(
3004 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003005 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003006 varDecl(hasInitializer(ignoringImpCasts(
3007 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003008 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003009 varDecl(hasInitializer(ignoringImpCasts(
3010 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003011 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003012 varDecl(hasInitializer(ignoringImpCasts(
3013 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003014}
3015
3016TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3017 // This test verifies that expressions that do not have implicit casts
3018 // still match the inner matcher.
3019 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003020 varDecl(hasInitializer(ignoringImpCasts(
3021 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003022}
3023
3024TEST(IgnoringParenCasts, MatchesParenCasts) {
3025 // This test checks that ignoringParenCasts matches when parentheses and/or
3026 // casts are present and its inner matcher alone does not match.
3027 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003028 varDecl(hasInitializer(ignoringParenCasts(
3029 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003030 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003031 varDecl(hasInitializer(ignoringParenCasts(
3032 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003033
3034 // This test creates an implict cast from int to char in addition to the
3035 // parentheses.
3036 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003037 varDecl(hasInitializer(ignoringParenCasts(
3038 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003039
3040 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003041 varDecl(hasInitializer(ignoringParenCasts(
3042 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003043 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003044 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003045 integerLiteral(equals(0)))))));
3046}
3047
3048TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3049 // This test verifies that expressions that do not have any casts still match.
3050 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003051 varDecl(hasInitializer(ignoringParenCasts(
3052 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003053}
3054
3055TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3056 // These tests verify that ignoringImpCasts does not match if the inner
3057 // matcher does not match.
3058 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003059 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003060 unless(anything()))))));
3061
3062 // This test creates an implicit cast from int to char in addition to the
3063 // parentheses.
3064 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003065 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003066 unless(anything()))))));
3067
3068 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003069 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003070 unless(anything()))))));
3071}
3072
3073TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3074 // This test checks that ignoringParenAndImpCasts matches when
3075 // parentheses and/or implicit casts are present and its inner matcher alone
3076 // does not match.
3077 // Note that this test creates an implicit const cast.
3078 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003079 varDecl(hasInitializer(ignoringParenImpCasts(
3080 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003081 // This test creates an implicit cast from int to char.
3082 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003083 varDecl(hasInitializer(ignoringParenImpCasts(
3084 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003085}
3086
3087TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3088 // This test verifies that expressions that do not have parentheses or
3089 // implicit casts still match.
3090 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003091 varDecl(hasInitializer(ignoringParenImpCasts(
3092 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003093 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003094 varDecl(hasInitializer(ignoringParenImpCasts(
3095 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003096}
3097
3098TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3099 // These tests verify that ignoringParenImpCasts does not match if
3100 // the inner matcher does not match.
3101 // This test creates an implicit cast.
3102 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003103 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003104 unless(anything()))))));
3105 // These tests verify that ignoringParenAndImplictCasts does not look
3106 // through explicit casts.
3107 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003108 varDecl(hasInitializer(ignoringParenImpCasts(
3109 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003110 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003111 varDecl(hasInitializer(ignoringParenImpCasts(
3112 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003113 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003114 varDecl(hasInitializer(ignoringParenImpCasts(
3115 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003116}
3117
Manuel Klimek715c9562012-07-25 10:02:02 +00003118TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek4da21662012-07-06 05:48:52 +00003119 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3120 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003121 implicitCastExpr(
3122 hasSourceExpression(constructExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003123}
3124
Manuel Klimek715c9562012-07-25 10:02:02 +00003125TEST(HasSourceExpression, MatchesExplicitCasts) {
3126 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003127 explicitCastExpr(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003128 hasSourceExpression(hasDescendant(
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003129 expr(integerLiteral()))))));
Manuel Klimek715c9562012-07-25 10:02:02 +00003130}
3131
Manuel Klimek4da21662012-07-06 05:48:52 +00003132TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003133 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00003134}
3135
3136TEST(Statement, MatchesCompoundStatments) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003137 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00003138}
3139
3140TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003141 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00003142}
3143
3144TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003145 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00003146}
3147
Stephen Hines651f13c2014-04-23 16:59:28 -07003148TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3149 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3150 "const Foo f = Foo();",
3151 varDecl(hasInitializer(exprWithCleanups()))));
3152 EXPECT_FALSE(matches("struct Foo { };"
3153 "const Foo f = Foo();",
3154 varDecl(hasInitializer(exprWithCleanups()))));
3155}
3156
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003157TEST(InitListExpression, MatchesInitListExpression) {
3158 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3159 initListExpr(hasType(asString("int [2]")))));
3160 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003161 initListExpr(hasType(recordDecl(hasName("B"))))));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003162 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3163 "void f();"
3164 "S s[1] = { &f };",
3165 declRefExpr(to(functionDecl(hasName("f"))))));
3166 EXPECT_TRUE(
3167 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003168}
3169
3170TEST(UsingDeclaration, MatchesUsingDeclarations) {
3171 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3172 usingDecl()));
3173}
3174
3175TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3176 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3177 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3178}
3179
3180TEST(UsingDeclaration, MatchesSpecificTarget) {
3181 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3182 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003183 hasTargetDecl(functionDecl())))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003184 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3185 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003186 hasTargetDecl(functionDecl())))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003187}
3188
3189TEST(UsingDeclaration, ThroughUsingDeclaration) {
3190 EXPECT_TRUE(matches(
3191 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003192 declRefExpr(throughUsingDecl(anything()))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003193 EXPECT_TRUE(notMatches(
3194 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003195 declRefExpr(throughUsingDecl(anything()))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003196}
3197
Stephen Hines176edba2014-12-01 14:53:08 -08003198TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3199 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3200 usingDirectiveDecl()));
3201 EXPECT_FALSE(
3202 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3203}
3204
Sam Panzer425f41b2012-08-16 17:20:59 +00003205TEST(SingleDecl, IsSingleDecl) {
3206 StatementMatcher SingleDeclStmt =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003207 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003208 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3209 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3210 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3211 SingleDeclStmt));
3212}
3213
3214TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003215 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzer425f41b2012-08-16 17:20:59 +00003216
3217 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003218 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003219 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003220 declStmt(containsDeclaration(0, MatchesInit),
3221 containsDeclaration(1, MatchesInit))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003222 unsigned WrongIndex = 42;
3223 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003224 declStmt(containsDeclaration(WrongIndex,
Sam Panzer425f41b2012-08-16 17:20:59 +00003225 MatchesInit))));
3226}
3227
3228TEST(DeclCount, DeclCountIsCorrect) {
3229 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003230 declStmt(declCountIs(2))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003231 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003232 declStmt(declCountIs(3))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003233 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003234 declStmt(declCountIs(3))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003235}
3236
Manuel Klimek4da21662012-07-06 05:48:52 +00003237TEST(While, MatchesWhileLoops) {
3238 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3239 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3240 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3241}
3242
3243TEST(Do, MatchesDoLoops) {
3244 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3245 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3246}
3247
3248TEST(Do, DoesNotMatchWhileLoops) {
3249 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3250}
3251
3252TEST(SwitchCase, MatchesCase) {
3253 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3254 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3255 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3256 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3257}
3258
Daniel Jasperb54b7642012-09-20 14:12:57 +00003259TEST(SwitchCase, MatchesSwitch) {
3260 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3261 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3262 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3263 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3264}
3265
Peter Collingbourneacf02712013-05-10 11:52:02 +00003266TEST(SwitchCase, MatchesEachCase) {
3267 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3268 switchStmt(forEachSwitchCase(caseStmt()))));
3269 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3270 switchStmt(forEachSwitchCase(caseStmt()))));
3271 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3272 switchStmt(forEachSwitchCase(caseStmt()))));
3273 EXPECT_TRUE(notMatches(
3274 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3275 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3276 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3277 switchStmt(forEachSwitchCase(
3278 caseStmt(hasCaseConstant(integerLiteral()))))));
3279 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3280 switchStmt(forEachSwitchCase(
3281 caseStmt(hasCaseConstant(integerLiteral()))))));
3282 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3283 switchStmt(forEachSwitchCase(
3284 caseStmt(hasCaseConstant(integerLiteral()))))));
3285 EXPECT_TRUE(matchAndVerifyResultTrue(
3286 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3287 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3288 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3289}
3290
Manuel Klimek06963012013-07-19 11:50:54 +00003291TEST(ForEachConstructorInitializer, MatchesInitializers) {
3292 EXPECT_TRUE(matches(
3293 "struct X { X() : i(42), j(42) {} int i, j; };",
3294 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3295}
3296
Daniel Jasperb54b7642012-09-20 14:12:57 +00003297TEST(ExceptionHandling, SimpleCases) {
3298 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3299 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3300 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3301 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3302 throwExpr()));
3303 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3304 throwExpr()));
3305}
3306
Manuel Klimek4da21662012-07-06 05:48:52 +00003307TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3308 EXPECT_TRUE(notMatches(
3309 "void x() { if(true) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003310 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003311 EXPECT_TRUE(notMatches(
3312 "void x() { int x; if((x = 42)) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003313 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003314}
3315
3316TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3317 EXPECT_TRUE(matches(
3318 "void x() { if(int* a = 0) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003319 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003320}
3321
3322TEST(ForEach, BindsOneNode) {
3323 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003324 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003325 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003326}
3327
3328TEST(ForEach, BindsMultipleNodes) {
3329 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003330 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003331 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003332}
3333
3334TEST(ForEach, BindsRecursiveCombinations) {
3335 EXPECT_TRUE(matchAndVerifyResultTrue(
3336 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003337 recordDecl(hasName("C"),
3338 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003339 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003340}
3341
3342TEST(ForEachDescendant, BindsOneNode) {
3343 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003344 recordDecl(hasName("C"),
3345 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003346 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003347}
3348
Daniel Jasper5f684e92012-11-16 18:39:22 +00003349TEST(ForEachDescendant, NestedForEachDescendant) {
3350 DeclarationMatcher m = recordDecl(
3351 isDefinition(), decl().bind("x"), hasName("C"));
3352 EXPECT_TRUE(matchAndVerifyResultTrue(
3353 "class A { class B { class C {}; }; };",
3354 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3355 new VerifyIdIsBoundTo<Decl>("x", "C")));
3356
Manuel Klimek054d0492013-06-19 15:42:45 +00003357 // Check that a partial match of 'm' that binds 'x' in the
3358 // first part of anyOf(m, anything()) will not overwrite the
3359 // binding created by the earlier binding in the hasDescendant.
3360 EXPECT_TRUE(matchAndVerifyResultTrue(
3361 "class A { class B { class C {}; }; };",
3362 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3363 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper5f684e92012-11-16 18:39:22 +00003364}
3365
Manuel Klimek4da21662012-07-06 05:48:52 +00003366TEST(ForEachDescendant, BindsMultipleNodes) {
3367 EXPECT_TRUE(matchAndVerifyResultTrue(
3368 "class C { class D { int x; int y; }; "
3369 " class E { class F { int y; int z; }; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003370 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003371 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003372}
3373
3374TEST(ForEachDescendant, BindsRecursiveCombinations) {
3375 EXPECT_TRUE(matchAndVerifyResultTrue(
3376 "class C { class D { "
3377 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003378 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3379 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003380 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003381}
3382
Manuel Klimek054d0492013-06-19 15:42:45 +00003383TEST(ForEachDescendant, BindsCombinations) {
3384 EXPECT_TRUE(matchAndVerifyResultTrue(
3385 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3386 "(true) {} }",
3387 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3388 forEachDescendant(whileStmt().bind("while"))),
3389 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3390}
3391
3392TEST(Has, DoesNotDeleteBindings) {
3393 EXPECT_TRUE(matchAndVerifyResultTrue(
3394 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3395 new VerifyIdIsBoundTo<Decl>("x", 1)));
3396}
3397
3398TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3399 // Those matchers cover all the cases where an inner matcher is called
3400 // and there is not a 1:1 relationship between the match of the outer
3401 // matcher and the match of the inner matcher.
3402 // The pattern to look for is:
3403 // ... return InnerMatcher.matches(...); ...
3404 // In which case no special handling is needed.
3405 //
3406 // On the other hand, if there are multiple alternative matches
3407 // (for example forEach*) or matches might be discarded (for example has*)
3408 // the implementation must make sure that the discarded matches do not
3409 // affect the bindings.
3410 // When new such matchers are added, add a test here that:
3411 // - matches a simple node, and binds it as the first thing in the matcher:
3412 // recordDecl(decl().bind("x"), hasName("X")))
3413 // - uses the matcher under test afterwards in a way that not the first
3414 // alternative is matched; for anyOf, that means the first branch
3415 // would need to return false; for hasAncestor, it means that not
3416 // the direct parent matches the inner matcher.
3417
3418 EXPECT_TRUE(matchAndVerifyResultTrue(
3419 "class X { int y; };",
3420 recordDecl(
3421 recordDecl().bind("x"), hasName("::X"),
3422 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3423 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3424 EXPECT_TRUE(matchAndVerifyResultTrue(
3425 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3426 anyOf(unless(anything()), anything())),
3427 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3428 EXPECT_TRUE(matchAndVerifyResultTrue(
3429 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3430 classTemplateSpecializationDecl(
3431 decl().bind("x"),
3432 hasAnyTemplateArgument(refersToType(asString("int")))),
3433 new VerifyIdIsBoundTo<Decl>("x", 1)));
3434 EXPECT_TRUE(matchAndVerifyResultTrue(
3435 "class X { void f(); void g(); };",
3436 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3437 new VerifyIdIsBoundTo<Decl>("x", 1)));
3438 EXPECT_TRUE(matchAndVerifyResultTrue(
3439 "class X { X() : a(1), b(2) {} double a; int b; };",
3440 recordDecl(decl().bind("x"),
3441 has(constructorDecl(
3442 hasAnyConstructorInitializer(forField(hasName("b")))))),
3443 new VerifyIdIsBoundTo<Decl>("x", 1)));
3444 EXPECT_TRUE(matchAndVerifyResultTrue(
3445 "void x(int, int) { x(0, 42); }",
3446 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3447 new VerifyIdIsBoundTo<Expr>("x", 1)));
3448 EXPECT_TRUE(matchAndVerifyResultTrue(
3449 "void x(int, int y) {}",
3450 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3451 new VerifyIdIsBoundTo<Decl>("x", 1)));
3452 EXPECT_TRUE(matchAndVerifyResultTrue(
3453 "void x() { return; if (true) {} }",
3454 functionDecl(decl().bind("x"),
3455 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3456 new VerifyIdIsBoundTo<Decl>("x", 1)));
3457 EXPECT_TRUE(matchAndVerifyResultTrue(
3458 "namespace X { void b(int); void b(); }"
3459 "using X::b;",
3460 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3461 functionDecl(parameterCountIs(1))))),
3462 new VerifyIdIsBoundTo<Decl>("x", 1)));
3463 EXPECT_TRUE(matchAndVerifyResultTrue(
3464 "class A{}; class B{}; class C : B, A {};",
3465 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3466 new VerifyIdIsBoundTo<Decl>("x", 1)));
3467 EXPECT_TRUE(matchAndVerifyResultTrue(
3468 "class A{}; typedef A B; typedef A C; typedef A D;"
3469 "class E : A {};",
3470 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3471 new VerifyIdIsBoundTo<Decl>("x", 1)));
3472 EXPECT_TRUE(matchAndVerifyResultTrue(
3473 "class A { class B { void f() {} }; };",
3474 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3475 new VerifyIdIsBoundTo<Decl>("x", 1)));
3476 EXPECT_TRUE(matchAndVerifyResultTrue(
3477 "template <typename T> struct A { struct B {"
3478 " void f() { if(true) {} }"
3479 "}; };"
3480 "void t() { A<int>::B b; b.f(); }",
3481 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3482 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3483 EXPECT_TRUE(matchAndVerifyResultTrue(
3484 "class A {};",
3485 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3486 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimek06963012013-07-19 11:50:54 +00003487 EXPECT_TRUE(matchAndVerifyResultTrue(
3488 "class A { A() : s(), i(42) {} const char *s; int i; };",
3489 constructorDecl(hasName("::A::A"), decl().bind("x"),
3490 forEachConstructorInitializer(forField(hasName("i")))),
3491 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimek054d0492013-06-19 15:42:45 +00003492}
3493
Daniel Jasper11c98772012-11-11 22:14:55 +00003494TEST(ForEachDescendant, BindsCorrectNodes) {
3495 EXPECT_TRUE(matchAndVerifyResultTrue(
3496 "class C { void f(); int i; };",
3497 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3498 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3499 EXPECT_TRUE(matchAndVerifyResultTrue(
3500 "class C { void f() {} int i; };",
3501 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3502 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3503}
3504
Manuel Klimek152ea0e2013-02-04 10:59:20 +00003505TEST(FindAll, BindsNodeOnMatch) {
3506 EXPECT_TRUE(matchAndVerifyResultTrue(
3507 "class A {};",
3508 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3509 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3510}
3511
3512TEST(FindAll, BindsDescendantNodeOnMatch) {
3513 EXPECT_TRUE(matchAndVerifyResultTrue(
3514 "class A { int a; int b; };",
3515 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3516 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3517}
3518
3519TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3520 EXPECT_TRUE(matchAndVerifyResultTrue(
3521 "class A { int a; int b; };",
3522 recordDecl(hasName("::A"),
3523 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3524 fieldDecl().bind("v"))))),
3525 new VerifyIdIsBoundTo<Decl>("v", 3)));
3526
3527 EXPECT_TRUE(matchAndVerifyResultTrue(
3528 "class A { class B {}; class C {}; };",
3529 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3530 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3531}
3532
Manuel Klimek73876732013-02-04 09:42:38 +00003533TEST(EachOf, TriggersForEachMatch) {
3534 EXPECT_TRUE(matchAndVerifyResultTrue(
3535 "class A { int a; int b; };",
3536 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3537 has(fieldDecl(hasName("b")).bind("v")))),
3538 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3539}
3540
3541TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3542 EXPECT_TRUE(matchAndVerifyResultTrue(
3543 "class A { int a; int c; };",
3544 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3545 has(fieldDecl(hasName("b")).bind("v")))),
3546 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3547 EXPECT_TRUE(matchAndVerifyResultTrue(
3548 "class A { int c; int b; };",
3549 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3550 has(fieldDecl(hasName("b")).bind("v")))),
3551 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3552 EXPECT_TRUE(notMatches(
3553 "class A { int c; int d; };",
3554 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3555 has(fieldDecl(hasName("b")).bind("v"))))));
3556}
Manuel Klimek4da21662012-07-06 05:48:52 +00003557
3558TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3559 // Make sure that we can both match the class by name (::X) and by the type
3560 // the template was instantiated with (via a field).
3561
3562 EXPECT_TRUE(matches(
3563 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003564 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003565
3566 EXPECT_TRUE(matches(
3567 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003568 recordDecl(isTemplateInstantiation(), hasDescendant(
3569 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003570}
3571
3572TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3573 EXPECT_TRUE(matches(
3574 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003575 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek4da21662012-07-06 05:48:52 +00003576 isTemplateInstantiation())));
3577}
3578
3579TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3580 EXPECT_TRUE(matches(
3581 "template <typename T> class X { T t; }; class A {};"
3582 "template class X<A>;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003583 recordDecl(isTemplateInstantiation(), hasDescendant(
3584 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003585}
3586
3587TEST(IsTemplateInstantiation,
3588 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3589 EXPECT_TRUE(matches(
3590 "template <typename T> class X {};"
3591 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003592 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003593}
3594
3595TEST(IsTemplateInstantiation,
3596 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3597 EXPECT_TRUE(matches(
3598 "class A {};"
3599 "class X {"
3600 " template <typename U> class Y { U u; };"
3601 " Y<A> y;"
3602 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003603 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003604}
3605
3606TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3607 // FIXME: Figure out whether this makes sense. It doesn't affect the
3608 // normal use case as long as the uppermost instantiation always is marked
3609 // as template instantiation, but it might be confusing as a predicate.
3610 EXPECT_TRUE(matches(
3611 "class A {};"
3612 "template <typename T> class X {"
3613 " template <typename U> class Y { U u; };"
3614 " Y<T> y;"
3615 "}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003616 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003617}
3618
3619TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3620 EXPECT_TRUE(notMatches(
3621 "template <typename T> class X {}; class A {};"
3622 "template <> class X<A> {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003623 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003624}
3625
3626TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3627 EXPECT_TRUE(notMatches(
3628 "class A {}; class Y { A a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003629 recordDecl(isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003630}
3631
Stephen Hines176edba2014-12-01 14:53:08 -08003632TEST(IsInstantiated, MatchesInstantiation) {
3633 EXPECT_TRUE(
3634 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3635 recordDecl(isInstantiated())));
3636}
3637
3638TEST(IsInstantiated, NotMatchesDefinition) {
3639 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3640 recordDecl(isInstantiated())));
3641}
3642
3643TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3644 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3645 "class Y { A<int> a; }; Y y;",
3646 declStmt(isInTemplateInstantiation())));
3647}
3648
3649TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3650 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3651 declStmt(isInTemplateInstantiation())));
3652}
3653
3654TEST(IsInstantiated, MatchesFunctionInstantiation) {
3655 EXPECT_TRUE(
3656 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3657 functionDecl(isInstantiated())));
3658}
3659
3660TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3661 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3662 varDecl(isInstantiated())));
3663}
3664
3665TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3666 EXPECT_TRUE(
3667 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3668 declStmt(isInTemplateInstantiation())));
3669}
3670
3671TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3672 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3673 declStmt(isInTemplateInstantiation())));
3674}
3675
3676TEST(IsInTemplateInstantiation, Sharing) {
3677 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3678 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3679 // and makes the matcher behave in non-obvious ways.
3680 EXPECT_TRUE(notMatches(
3681 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3682 Matcher));
3683 EXPECT_TRUE(matches(
3684 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3685 Matcher));
3686}
3687
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003688TEST(IsExplicitTemplateSpecialization,
3689 DoesNotMatchPrimaryTemplate) {
3690 EXPECT_TRUE(notMatches(
3691 "template <typename T> class X {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003692 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003693 EXPECT_TRUE(notMatches(
3694 "template <typename T> void f(T t);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003695 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003696}
3697
3698TEST(IsExplicitTemplateSpecialization,
3699 DoesNotMatchExplicitTemplateInstantiations) {
3700 EXPECT_TRUE(notMatches(
3701 "template <typename T> class X {};"
3702 "template class X<int>; extern template class X<long>;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003703 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003704 EXPECT_TRUE(notMatches(
3705 "template <typename T> void f(T t) {}"
3706 "template void f(int t); extern template void f(long t);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003707 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003708}
3709
3710TEST(IsExplicitTemplateSpecialization,
3711 DoesNotMatchImplicitTemplateInstantiations) {
3712 EXPECT_TRUE(notMatches(
3713 "template <typename T> class X {}; X<int> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003714 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003715 EXPECT_TRUE(notMatches(
3716 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003717 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003718}
3719
3720TEST(IsExplicitTemplateSpecialization,
3721 MatchesExplicitTemplateSpecializations) {
3722 EXPECT_TRUE(matches(
3723 "template <typename T> class X {};"
3724 "template<> class X<int> {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003725 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003726 EXPECT_TRUE(matches(
3727 "template <typename T> void f(T t) {}"
3728 "template<> void f(int t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003729 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003730}
3731
Manuel Klimek579b1202012-09-07 09:26:10 +00003732TEST(HasAncenstor, MatchesDeclarationAncestors) {
3733 EXPECT_TRUE(matches(
3734 "class A { class B { class C {}; }; };",
3735 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3736}
3737
3738TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3739 EXPECT_TRUE(notMatches(
3740 "class A { class B { class C {}; }; };",
3741 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3742}
3743
3744TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3745 EXPECT_TRUE(matches(
3746 "class A { class B { void f() { C c; } class C {}; }; };",
3747 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3748 hasAncestor(recordDecl(hasName("A"))))))));
3749}
3750
3751TEST(HasAncenstor, MatchesStatementAncestors) {
3752 EXPECT_TRUE(matches(
3753 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003754 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek579b1202012-09-07 09:26:10 +00003755}
3756
3757TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3758 EXPECT_TRUE(matches(
3759 "void f() { if (true) { int x = 42; } }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003760 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek579b1202012-09-07 09:26:10 +00003761}
3762
3763TEST(HasAncestor, BindsRecursiveCombinations) {
3764 EXPECT_TRUE(matchAndVerifyResultTrue(
3765 "class C { class D { class E { class F { int y; }; }; }; };",
3766 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003767 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek579b1202012-09-07 09:26:10 +00003768}
3769
3770TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3771 EXPECT_TRUE(matchAndVerifyResultTrue(
3772 "class C { class D { class E { class F { int y; }; }; }; };",
3773 fieldDecl(hasAncestor(
3774 decl(
3775 hasDescendant(recordDecl(isDefinition(),
3776 hasAncestor(recordDecl())))
3777 ).bind("d")
3778 )),
Daniel Jaspera7564432012-09-13 13:11:25 +00003779 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek579b1202012-09-07 09:26:10 +00003780}
3781
Manuel Klimek374516c2013-03-14 16:33:21 +00003782TEST(HasAncestor, MatchesClosestAncestor) {
3783 EXPECT_TRUE(matchAndVerifyResultTrue(
3784 "template <typename T> struct C {"
3785 " void f(int) {"
3786 " struct I { void g(T) { int x; } } i; i.g(42);"
3787 " }"
3788 "};"
3789 "template struct C<int>;",
3790 varDecl(hasName("x"),
3791 hasAncestor(functionDecl(hasParameter(
3792 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3793 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3794}
3795
Manuel Klimek579b1202012-09-07 09:26:10 +00003796TEST(HasAncestor, MatchesInTemplateInstantiations) {
3797 EXPECT_TRUE(matches(
3798 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3799 "A<int>::B::C a;",
3800 fieldDecl(hasType(asString("int")),
3801 hasAncestor(recordDecl(hasName("A"))))));
3802}
3803
3804TEST(HasAncestor, MatchesInImplicitCode) {
3805 EXPECT_TRUE(matches(
3806 "struct X {}; struct A { A() {} X x; };",
3807 constructorDecl(
3808 hasAnyConstructorInitializer(withInitializer(expr(
3809 hasAncestor(recordDecl(hasName("A")))))))));
3810}
3811
Daniel Jasperc99a3ad2012-10-22 16:26:51 +00003812TEST(HasParent, MatchesOnlyParent) {
3813 EXPECT_TRUE(matches(
3814 "void f() { if (true) { int x = 42; } }",
3815 compoundStmt(hasParent(ifStmt()))));
3816 EXPECT_TRUE(notMatches(
3817 "void f() { for (;;) { int x = 42; } }",
3818 compoundStmt(hasParent(ifStmt()))));
3819 EXPECT_TRUE(notMatches(
3820 "void f() { if (true) for (;;) { int x = 42; } }",
3821 compoundStmt(hasParent(ifStmt()))));
3822}
3823
Manuel Klimek30ace372012-12-06 14:42:48 +00003824TEST(HasAncestor, MatchesAllAncestors) {
3825 EXPECT_TRUE(matches(
3826 "template <typename T> struct C { static void f() { 42; } };"
3827 "void t() { C<int>::f(); }",
3828 integerLiteral(
3829 equals(42),
3830 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3831 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3832}
3833
3834TEST(HasParent, MatchesAllParents) {
3835 EXPECT_TRUE(matches(
3836 "template <typename T> struct C { static void f() { 42; } };"
3837 "void t() { C<int>::f(); }",
3838 integerLiteral(
3839 equals(42),
3840 hasParent(compoundStmt(hasParent(functionDecl(
3841 hasParent(recordDecl(isTemplateInstantiation())))))))));
3842 EXPECT_TRUE(matches(
3843 "template <typename T> struct C { static void f() { 42; } };"
3844 "void t() { C<int>::f(); }",
3845 integerLiteral(
3846 equals(42),
3847 hasParent(compoundStmt(hasParent(functionDecl(
3848 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3849 EXPECT_TRUE(matches(
3850 "template <typename T> struct C { static void f() { 42; } };"
3851 "void t() { C<int>::f(); }",
3852 integerLiteral(equals(42),
3853 hasParent(compoundStmt(allOf(
3854 hasParent(functionDecl(
3855 hasParent(recordDecl(isTemplateInstantiation())))),
3856 hasParent(functionDecl(hasParent(recordDecl(
3857 unless(isTemplateInstantiation())))))))))));
Manuel Klimek374516c2013-03-14 16:33:21 +00003858 EXPECT_TRUE(
3859 notMatches("template <typename T> struct C { static void f() {} };"
3860 "void t() { C<int>::f(); }",
3861 compoundStmt(hasParent(recordDecl()))));
Manuel Klimek30ace372012-12-06 14:42:48 +00003862}
3863
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003864TEST(HasParent, NoDuplicateParents) {
3865 class HasDuplicateParents : public BoundNodesCallback {
3866 public:
3867 bool run(const BoundNodes *Nodes) override { return false; }
3868 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3869 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3870 std::set<const void *> Parents;
3871 for (const auto &Parent : Context->getParents(*Node)) {
3872 if (!Parents.insert(Parent.getMemoizationData()).second) {
3873 return true;
3874 }
3875 }
3876 return false;
3877 }
3878 };
3879 EXPECT_FALSE(matchAndVerifyResultTrue(
3880 "template <typename T> int Foo() { return 1 + 2; }\n"
3881 "int x = Foo<int>() + Foo<unsigned>();",
3882 stmt().bind("node"), new HasDuplicateParents()));
3883}
3884
Daniel Jasperce620072012-10-17 08:52:59 +00003885TEST(TypeMatching, MatchesTypes) {
3886 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3887}
3888
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003889TEST(TypeMatching, MatchesVoid) {
3890 EXPECT_TRUE(
3891 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
3892}
3893
Daniel Jasperce620072012-10-17 08:52:59 +00003894TEST(TypeMatching, MatchesArrayTypes) {
3895 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3896 EXPECT_TRUE(matches("int a[42];", arrayType()));
3897 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3898
3899 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3900 arrayType(hasElementType(builtinType()))));
3901
3902 EXPECT_TRUE(matches(
3903 "int const a[] = { 2, 3 };",
3904 qualType(arrayType(hasElementType(builtinType())))));
3905 EXPECT_TRUE(matches(
3906 "int const a[] = { 2, 3 };",
3907 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3908 EXPECT_TRUE(matches(
3909 "typedef const int T; T x[] = { 1, 2 };",
3910 qualType(isConstQualified(), arrayType())));
3911
3912 EXPECT_TRUE(notMatches(
3913 "int a[] = { 2, 3 };",
3914 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3915 EXPECT_TRUE(notMatches(
3916 "int a[] = { 2, 3 };",
3917 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3918 EXPECT_TRUE(notMatches(
3919 "int const a[] = { 2, 3 };",
3920 qualType(arrayType(hasElementType(builtinType())),
3921 unless(isConstQualified()))));
3922
3923 EXPECT_TRUE(matches("int a[2];",
3924 constantArrayType(hasElementType(builtinType()))));
3925 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3926}
3927
3928TEST(TypeMatching, MatchesComplexTypes) {
3929 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3930 EXPECT_TRUE(matches(
3931 "_Complex float f;",
3932 complexType(hasElementType(builtinType()))));
3933 EXPECT_TRUE(notMatches(
3934 "_Complex float f;",
3935 complexType(hasElementType(isInteger()))));
3936}
3937
3938TEST(TypeMatching, MatchesConstantArrayTypes) {
3939 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3940 EXPECT_TRUE(notMatches(
3941 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3942 constantArrayType(hasElementType(builtinType()))));
3943
3944 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3945 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3946 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3947}
3948
3949TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3950 EXPECT_TRUE(matches(
3951 "template <typename T, int Size> class array { T data[Size]; };",
3952 dependentSizedArrayType()));
3953 EXPECT_TRUE(notMatches(
3954 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3955 dependentSizedArrayType()));
3956}
3957
3958TEST(TypeMatching, MatchesIncompleteArrayType) {
3959 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3960 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3961
3962 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3963 incompleteArrayType()));
3964}
3965
3966TEST(TypeMatching, MatchesVariableArrayType) {
3967 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3968 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3969
3970 EXPECT_TRUE(matches(
3971 "void f(int b) { int a[b]; }",
3972 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3973 varDecl(hasName("b")))))))));
3974}
3975
3976TEST(TypeMatching, MatchesAtomicTypes) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003977 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3978 llvm::Triple::Win32) {
3979 // FIXME: Make this work for MSVC.
3980 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasperce620072012-10-17 08:52:59 +00003981
Stephen Hines651f13c2014-04-23 16:59:28 -07003982 EXPECT_TRUE(matches("_Atomic(int) i;",
3983 atomicType(hasValueType(isInteger()))));
3984 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3985 atomicType(hasValueType(isInteger()))));
3986 }
Daniel Jasperce620072012-10-17 08:52:59 +00003987}
3988
3989TEST(TypeMatching, MatchesAutoTypes) {
3990 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3991 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3992 autoType()));
3993
Richard Smith9b131752013-04-30 21:23:01 +00003994 // FIXME: Matching against the type-as-written can't work here, because the
3995 // type as written was not deduced.
3996 //EXPECT_TRUE(matches("auto a = 1;",
3997 // autoType(hasDeducedType(isInteger()))));
3998 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3999 // autoType(hasDeducedType(isInteger()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004000}
4001
Daniel Jaspera267cf62012-10-29 10:14:44 +00004002TEST(TypeMatching, MatchesFunctionTypes) {
4003 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4004 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4005}
4006
Edwin Vane88be2fd2013-04-01 18:33:34 +00004007TEST(TypeMatching, MatchesParenType) {
4008 EXPECT_TRUE(
4009 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4010 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4011
4012 EXPECT_TRUE(matches(
4013 "int (*ptr_to_func)(int);",
4014 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4015 EXPECT_TRUE(notMatches(
4016 "int (*ptr_to_array)[4];",
4017 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4018}
4019
Daniel Jasperce620072012-10-17 08:52:59 +00004020TEST(TypeMatching, PointerTypes) {
Daniel Jasper1802daf2012-10-17 13:35:36 +00004021 // FIXME: Reactive when these tests can be more specific (not matching
4022 // implicit code on certain platforms), likely when we have hasDescendant for
4023 // Types/TypeLocs.
4024 //EXPECT_TRUE(matchAndVerifyResultTrue(
4025 // "int* a;",
4026 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4027 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4028 //EXPECT_TRUE(matchAndVerifyResultTrue(
4029 // "int* a;",
4030 // pointerTypeLoc().bind("loc"),
4031 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasperce620072012-10-17 08:52:59 +00004032 EXPECT_TRUE(matches(
4033 "int** a;",
David Blaikie5be093c2013-02-18 19:04:16 +00004034 loc(pointerType(pointee(qualType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00004035 EXPECT_TRUE(matches(
4036 "int** a;",
4037 loc(pointerType(pointee(pointerType())))));
4038 EXPECT_TRUE(matches(
4039 "int* b; int* * const a = &b;",
4040 loc(qualType(isConstQualified(), pointerType()))));
4041
4042 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper1802daf2012-10-17 13:35:36 +00004043 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4044 hasType(blockPointerType()))));
4045 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4046 hasType(memberPointerType()))));
4047 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4048 hasType(pointerType()))));
4049 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4050 hasType(referenceType()))));
Edwin Vanef4b48042013-03-07 15:44:40 +00004051 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4052 hasType(lValueReferenceType()))));
4053 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4054 hasType(rValueReferenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004055
Daniel Jasper1802daf2012-10-17 13:35:36 +00004056 Fragment = "int *ptr;";
4057 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4058 hasType(blockPointerType()))));
4059 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4060 hasType(memberPointerType()))));
4061 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4062 hasType(pointerType()))));
4063 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4064 hasType(referenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004065
Daniel Jasper1802daf2012-10-17 13:35:36 +00004066 Fragment = "int a; int &ref = a;";
4067 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4068 hasType(blockPointerType()))));
4069 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4070 hasType(memberPointerType()))));
4071 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4072 hasType(pointerType()))));
4073 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4074 hasType(referenceType()))));
Edwin Vanef4b48042013-03-07 15:44:40 +00004075 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4076 hasType(lValueReferenceType()))));
4077 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4078 hasType(rValueReferenceType()))));
4079
4080 Fragment = "int &&ref = 2;";
4081 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4082 hasType(blockPointerType()))));
4083 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4084 hasType(memberPointerType()))));
4085 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4086 hasType(pointerType()))));
4087 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4088 hasType(referenceType()))));
4089 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4090 hasType(lValueReferenceType()))));
4091 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4092 hasType(rValueReferenceType()))));
4093}
4094
4095TEST(TypeMatching, AutoRefTypes) {
4096 std::string Fragment = "auto a = 1;"
4097 "auto b = a;"
4098 "auto &c = a;"
4099 "auto &&d = c;"
4100 "auto &&e = 2;";
4101 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4102 hasType(referenceType()))));
4103 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4104 hasType(referenceType()))));
4105 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4106 hasType(referenceType()))));
4107 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4108 hasType(lValueReferenceType()))));
4109 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4110 hasType(rValueReferenceType()))));
4111 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4112 hasType(referenceType()))));
4113 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4114 hasType(lValueReferenceType()))));
4115 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4116 hasType(rValueReferenceType()))));
4117 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4118 hasType(referenceType()))));
4119 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4120 hasType(lValueReferenceType()))));
4121 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4122 hasType(rValueReferenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004123}
4124
4125TEST(TypeMatching, PointeeTypes) {
4126 EXPECT_TRUE(matches("int b; int &a = b;",
4127 referenceType(pointee(builtinType()))));
4128 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4129
4130 EXPECT_TRUE(matches("int *a;",
David Blaikie5be093c2013-02-18 19:04:16 +00004131 loc(pointerType(pointee(builtinType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00004132
4133 EXPECT_TRUE(matches(
4134 "int const *A;",
4135 pointerType(pointee(isConstQualified(), builtinType()))));
4136 EXPECT_TRUE(notMatches(
4137 "int *A;",
4138 pointerType(pointee(isConstQualified(), builtinType()))));
4139}
4140
4141TEST(TypeMatching, MatchesPointersToConstTypes) {
4142 EXPECT_TRUE(matches("int b; int * const a = &b;",
4143 loc(pointerType())));
4144 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikie5be093c2013-02-18 19:04:16 +00004145 loc(pointerType())));
Daniel Jasperce620072012-10-17 08:52:59 +00004146 EXPECT_TRUE(matches(
4147 "int b; const int * a = &b;",
David Blaikie5be093c2013-02-18 19:04:16 +00004148 loc(pointerType(pointee(builtinType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00004149 EXPECT_TRUE(matches(
4150 "int b; const int * a = &b;",
4151 pointerType(pointee(builtinType()))));
4152}
4153
4154TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper1802daf2012-10-17 13:35:36 +00004155 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4156 hasType(typedefType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004157}
4158
Edwin Vane3abf7782013-02-25 14:49:29 +00004159TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vane742d9e72013-02-25 20:43:32 +00004160 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vane3abf7782013-02-25 14:49:29 +00004161 templateSpecializationType()));
4162}
4163
Edwin Vane742d9e72013-02-25 20:43:32 +00004164TEST(TypeMatching, MatchesRecordType) {
4165 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek0cc798f2013-02-27 11:56:58 +00004166 EXPECT_TRUE(matches("struct S{}; S s;",
4167 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4168 EXPECT_TRUE(notMatches("int i;",
4169 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vane742d9e72013-02-25 20:43:32 +00004170}
4171
4172TEST(TypeMatching, MatchesElaboratedType) {
4173 EXPECT_TRUE(matches(
4174 "namespace N {"
4175 " namespace M {"
4176 " class D {};"
4177 " }"
4178 "}"
4179 "N::M::D d;", elaboratedType()));
4180 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4181 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4182}
4183
4184TEST(ElaboratedTypeNarrowing, hasQualifier) {
4185 EXPECT_TRUE(matches(
4186 "namespace N {"
4187 " namespace M {"
4188 " class D {};"
4189 " }"
4190 "}"
4191 "N::M::D d;",
4192 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4193 EXPECT_TRUE(notMatches(
4194 "namespace M {"
4195 " class D {};"
4196 "}"
4197 "M::D d;",
4198 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vaneaec89ac2013-03-04 17:51:00 +00004199 EXPECT_TRUE(notMatches(
4200 "struct D {"
4201 "} d;",
4202 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vane742d9e72013-02-25 20:43:32 +00004203}
4204
4205TEST(ElaboratedTypeNarrowing, namesType) {
4206 EXPECT_TRUE(matches(
4207 "namespace N {"
4208 " namespace M {"
4209 " class D {};"
4210 " }"
4211 "}"
4212 "N::M::D d;",
4213 elaboratedType(elaboratedType(namesType(recordType(
4214 hasDeclaration(namedDecl(hasName("D")))))))));
4215 EXPECT_TRUE(notMatches(
4216 "namespace M {"
4217 " class D {};"
4218 "}"
4219 "M::D d;",
4220 elaboratedType(elaboratedType(namesType(typedefType())))));
4221}
4222
Daniel Jaspera7564432012-09-13 13:11:25 +00004223TEST(NNS, MatchesNestedNameSpecifiers) {
4224 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4225 nestedNameSpecifier()));
4226 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4227 nestedNameSpecifier()));
4228 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4229 nestedNameSpecifier()));
4230
4231 EXPECT_TRUE(matches(
4232 "struct A { static void f() {} }; void g() { A::f(); }",
4233 nestedNameSpecifier()));
4234 EXPECT_TRUE(notMatches(
4235 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4236 nestedNameSpecifier()));
4237}
4238
Daniel Jasperb54b7642012-09-20 14:12:57 +00004239TEST(NullStatement, SimpleCases) {
4240 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4241 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4242}
4243
Daniel Jaspera7564432012-09-13 13:11:25 +00004244TEST(NNS, MatchesTypes) {
4245 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4246 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4247 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4248 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4249 Matcher));
4250 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4251}
4252
4253TEST(NNS, MatchesNamespaceDecls) {
4254 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4255 specifiesNamespace(hasName("ns")));
4256 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4257 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4258 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4259}
4260
4261TEST(NNS, BindsNestedNameSpecifiers) {
4262 EXPECT_TRUE(matchAndVerifyResultTrue(
4263 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4264 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4265 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4266}
4267
4268TEST(NNS, BindsNestedNameSpecifierLocs) {
4269 EXPECT_TRUE(matchAndVerifyResultTrue(
4270 "namespace ns { struct B {}; } ns::B b;",
4271 loc(nestedNameSpecifier()).bind("loc"),
4272 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4273}
4274
4275TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4276 EXPECT_TRUE(matches(
4277 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4278 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4279 EXPECT_TRUE(matches(
4280 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasperce620072012-10-17 08:52:59 +00004281 nestedNameSpecifierLoc(hasPrefix(
4282 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera7564432012-09-13 13:11:25 +00004283}
4284
Daniel Jasperd1ce3c12012-10-30 15:42:00 +00004285TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4286 std::string Fragment =
4287 "namespace a { struct A { struct B { struct C {}; }; }; };"
4288 "void f() { a::A::B::C c; }";
4289 EXPECT_TRUE(matches(
4290 Fragment,
4291 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4292 hasDescendant(nestedNameSpecifier(
4293 specifiesNamespace(hasName("a")))))));
4294 EXPECT_TRUE(notMatches(
4295 Fragment,
4296 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4297 has(nestedNameSpecifier(
4298 specifiesNamespace(hasName("a")))))));
4299 EXPECT_TRUE(matches(
4300 Fragment,
4301 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4302 has(nestedNameSpecifier(
4303 specifiesNamespace(hasName("a")))))));
4304
4305 // Not really useful because a NestedNameSpecifier can af at most one child,
4306 // but to complete the interface.
4307 EXPECT_TRUE(matchAndVerifyResultTrue(
4308 Fragment,
4309 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4310 forEach(nestedNameSpecifier().bind("x"))),
4311 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4312}
4313
4314TEST(NNS, NestedNameSpecifiersAsDescendants) {
4315 std::string Fragment =
4316 "namespace a { struct A { struct B { struct C {}; }; }; };"
4317 "void f() { a::A::B::C c; }";
4318 EXPECT_TRUE(matches(
4319 Fragment,
4320 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4321 asString("struct a::A")))))));
4322 EXPECT_TRUE(matchAndVerifyResultTrue(
4323 Fragment,
4324 functionDecl(hasName("f"),
4325 forEachDescendant(nestedNameSpecifier().bind("x"))),
4326 // Nested names: a, a::A and a::A::B.
4327 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4328}
4329
4330TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4331 std::string Fragment =
4332 "namespace a { struct A { struct B { struct C {}; }; }; };"
4333 "void f() { a::A::B::C c; }";
4334 EXPECT_TRUE(matches(
4335 Fragment,
4336 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4337 hasDescendant(loc(nestedNameSpecifier(
4338 specifiesNamespace(hasName("a"))))))));
4339 EXPECT_TRUE(notMatches(
4340 Fragment,
4341 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4342 has(loc(nestedNameSpecifier(
4343 specifiesNamespace(hasName("a"))))))));
4344 EXPECT_TRUE(matches(
4345 Fragment,
4346 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4347 has(loc(nestedNameSpecifier(
4348 specifiesNamespace(hasName("a"))))))));
4349
4350 EXPECT_TRUE(matchAndVerifyResultTrue(
4351 Fragment,
4352 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4353 forEach(nestedNameSpecifierLoc().bind("x"))),
4354 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4355}
4356
4357TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4358 std::string Fragment =
4359 "namespace a { struct A { struct B { struct C {}; }; }; };"
4360 "void f() { a::A::B::C c; }";
4361 EXPECT_TRUE(matches(
4362 Fragment,
4363 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4364 asString("struct a::A"))))))));
4365 EXPECT_TRUE(matchAndVerifyResultTrue(
4366 Fragment,
4367 functionDecl(hasName("f"),
4368 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4369 // Nested names: a, a::A and a::A::B.
4370 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4371}
4372
Manuel Klimek60969f52013-02-01 13:41:35 +00004373template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004374public:
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004375 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4376 StringRef InnerId)
4377 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jasper452abbc2012-10-29 10:48:25 +00004378 }
4379
Manuel Klimek60969f52013-02-01 13:41:35 +00004380 virtual bool run(const BoundNodes *Nodes) { return false; }
4381
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004382 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4383 const T *Node = Nodes->getNodeAs<T>(Id);
Stephen Hines176edba2014-12-01 14:53:08 -08004384 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4385 nullptr;
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004386 }
4387private:
4388 std::string Id;
4389 internal::Matcher<T> InnerMatcher;
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004390 std::string InnerId;
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004391};
4392
4393TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek60969f52013-02-01 13:41:35 +00004394 EXPECT_TRUE(matchAndVerifyResultTrue(
4395 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4396 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004397 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4398 "Y")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004399 EXPECT_TRUE(matchAndVerifyResultFalse(
4400 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4401 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004402 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4403 "Z")));
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004404}
4405
4406TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek60969f52013-02-01 13:41:35 +00004407 EXPECT_TRUE(matchAndVerifyResultTrue(
4408 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004409 new VerifyMatchOnNode<clang::Stmt>(
4410 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004411 EXPECT_TRUE(matchAndVerifyResultFalse(
4412 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004413 new VerifyMatchOnNode<clang::Stmt>(
4414 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004415}
4416
4417TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4418 EXPECT_TRUE(matchAndVerifyResultTrue(
4419 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4420 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004421 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004422 EXPECT_TRUE(matchAndVerifyResultFalse(
4423 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4424 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004425 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004426}
4427
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004428template <typename T>
4429class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4430public:
4431 virtual bool run(const BoundNodes *Nodes) { return false; }
4432
4433 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4434 const T *Node = Nodes->getNodeAs<T>("");
4435 return verify(*Nodes, *Context, Node);
4436 }
4437
4438 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004439 // Use the original typed pointer to verify we can pass pointers to subtypes
4440 // to equalsNode.
4441 const T *TypedNode = cast<T>(Node);
Stephen Hines176edba2014-12-01 14:53:08 -08004442 return selectFirst<T>(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004443 "", match(stmt(hasParent(
4444 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004445 *Node, Context)) != nullptr;
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004446 }
4447 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004448 // Use the original typed pointer to verify we can pass pointers to subtypes
4449 // to equalsNode.
4450 const T *TypedNode = cast<T>(Node);
Stephen Hines176edba2014-12-01 14:53:08 -08004451 return selectFirst<T>(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004452 "", match(decl(hasParent(
4453 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004454 *Node, Context)) != nullptr;
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004455 }
4456};
4457
4458TEST(IsEqualTo, MatchesNodesByIdentity) {
4459 EXPECT_TRUE(matchAndVerifyResultTrue(
4460 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004461 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4462 EXPECT_TRUE(matchAndVerifyResultTrue(
4463 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4464 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004465}
4466
Stephen Hines176edba2014-12-01 14:53:08 -08004467TEST(MatchFinder, CheckProfiling) {
4468 MatchFinder::MatchFinderOptions Options;
4469 llvm::StringMap<llvm::TimeRecord> Records;
4470 Options.CheckProfiling.emplace(Records);
4471 MatchFinder Finder(std::move(Options));
4472
4473 struct NamedCallback : public MatchFinder::MatchCallback {
4474 void run(const MatchFinder::MatchResult &Result) override {}
4475 StringRef getID() const override { return "MyID"; }
4476 } Callback;
4477 Finder.addMatcher(decl(), &Callback);
4478 std::unique_ptr<FrontendActionFactory> Factory(
4479 newFrontendActionFactory(&Finder));
4480 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4481
4482 EXPECT_EQ(1u, Records.size());
4483 EXPECT_EQ("MyID", Records.begin()->getKey());
4484}
4485
Manuel Klimeke5793282012-11-02 01:31:03 +00004486class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4487public:
4488 VerifyStartOfTranslationUnit() : Called(false) {}
4489 virtual void run(const MatchFinder::MatchResult &Result) {
4490 EXPECT_TRUE(Called);
4491 }
4492 virtual void onStartOfTranslationUnit() {
4493 Called = true;
4494 }
4495 bool Called;
4496};
4497
4498TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4499 MatchFinder Finder;
4500 VerifyStartOfTranslationUnit VerifyCallback;
4501 Finder.addMatcher(decl(), &VerifyCallback);
Stephen Hines651f13c2014-04-23 16:59:28 -07004502 std::unique_ptr<FrontendActionFactory> Factory(
4503 newFrontendActionFactory(&Finder));
Manuel Klimeke5793282012-11-02 01:31:03 +00004504 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4505 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004506
4507 VerifyCallback.Called = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004508 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004509 ASSERT_TRUE(AST.get());
4510 Finder.matchAST(AST->getASTContext());
4511 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimeke5793282012-11-02 01:31:03 +00004512}
4513
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004514class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4515public:
4516 VerifyEndOfTranslationUnit() : Called(false) {}
4517 virtual void run(const MatchFinder::MatchResult &Result) {
4518 EXPECT_FALSE(Called);
4519 }
4520 virtual void onEndOfTranslationUnit() {
4521 Called = true;
4522 }
4523 bool Called;
4524};
4525
4526TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4527 MatchFinder Finder;
4528 VerifyEndOfTranslationUnit VerifyCallback;
4529 Finder.addMatcher(decl(), &VerifyCallback);
Stephen Hines651f13c2014-04-23 16:59:28 -07004530 std::unique_ptr<FrontendActionFactory> Factory(
4531 newFrontendActionFactory(&Finder));
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004532 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4533 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004534
4535 VerifyCallback.Called = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004536 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004537 ASSERT_TRUE(AST.get());
4538 Finder.matchAST(AST->getASTContext());
4539 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004540}
4541
Manuel Klimekcf52ca62013-06-20 14:06:32 +00004542TEST(EqualsBoundNodeMatcher, QualType) {
4543 EXPECT_TRUE(matches(
4544 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4545 hasInitializer(ignoringParenImpCasts(
4546 hasType(qualType(equalsBoundNode("type"))))))));
4547 EXPECT_TRUE(notMatches("int i = 1.f;",
4548 varDecl(hasType(qualType().bind("type")),
4549 hasInitializer(ignoringParenImpCasts(hasType(
4550 qualType(equalsBoundNode("type"))))))));
4551}
4552
4553TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4554 EXPECT_TRUE(notMatches(
4555 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4556 hasInitializer(ignoringParenImpCasts(
4557 hasType(qualType(equalsBoundNode("type"))))))));
4558}
4559
4560TEST(EqualsBoundNodeMatcher, Stmt) {
4561 EXPECT_TRUE(
4562 matches("void f() { if(true) {} }",
4563 stmt(allOf(ifStmt().bind("if"),
4564 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4565
4566 EXPECT_TRUE(notMatches(
4567 "void f() { if(true) { if (true) {} } }",
4568 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4569}
4570
4571TEST(EqualsBoundNodeMatcher, Decl) {
4572 EXPECT_TRUE(matches(
4573 "class X { class Y {}; };",
4574 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4575 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4576
4577 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4578 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4579 has(decl(equalsBoundNode("record")))))));
4580}
4581
4582TEST(EqualsBoundNodeMatcher, Type) {
4583 EXPECT_TRUE(matches(
4584 "class X { int a; int b; };",
4585 recordDecl(
4586 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4587 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4588
4589 EXPECT_TRUE(notMatches(
4590 "class X { int a; double b; };",
4591 recordDecl(
4592 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4593 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4594}
4595
4596TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekcf52ca62013-06-20 14:06:32 +00004597 EXPECT_TRUE(matchAndVerifyResultTrue(
4598 "int f() {"
4599 " if (1) {"
4600 " int i = 9;"
4601 " }"
4602 " int j = 10;"
4603 " {"
4604 " float k = 9.0;"
4605 " }"
4606 " return 0;"
4607 "}",
4608 // Look for variable declarations within functions whose type is the same
4609 // as the function return type.
4610 functionDecl(returns(qualType().bind("type")),
4611 forEachDescendant(varDecl(hasType(
4612 qualType(equalsBoundNode("type")))).bind("decl"))),
4613 // Only i and j should match, not k.
4614 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4615}
4616
4617TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4618 EXPECT_TRUE(matchAndVerifyResultTrue(
4619 "void f() {"
4620 " int x;"
4621 " double d;"
4622 " x = d + x - d + x;"
4623 "}",
4624 functionDecl(
4625 hasName("f"), forEachDescendant(varDecl().bind("d")),
4626 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4627 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4628}
4629
Stephen Hines651f13c2014-04-23 16:59:28 -07004630TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4631 EXPECT_TRUE(matchAndVerifyResultTrue(
4632 "struct StringRef { int size() const; const char* data() const; };"
4633 "void f(StringRef v) {"
4634 " v.data();"
4635 "}",
4636 memberCallExpr(
4637 callee(methodDecl(hasName("data"))),
4638 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4639 .bind("var")))),
4640 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4641 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4642 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4643 .bind("data"),
4644 new VerifyIdIsBoundTo<Expr>("data", 1)));
4645
4646 EXPECT_FALSE(matches(
4647 "struct StringRef { int size() const; const char* data() const; };"
4648 "void f(StringRef v) {"
4649 " v.data();"
4650 " v.size();"
4651 "}",
4652 memberCallExpr(
4653 callee(methodDecl(hasName("data"))),
4654 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4655 .bind("var")))),
4656 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4657 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4658 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4659 .bind("data")));
4660}
4661
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004662TEST(TypeDefDeclMatcher, Match) {
4663 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4664 typedefDecl(hasName("typedefDeclTest"))));
4665}
4666
4667// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4668#ifndef LLVM_ON_WIN32
4669
4670TEST(Matcher, IsExpansionInMainFileMatcher) {
4671 EXPECT_TRUE(matches("class X {};",
4672 recordDecl(hasName("X"), isExpansionInMainFile())));
4673 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4674 FileContentMappings M;
4675 M.push_back(std::make_pair("/other", "class X {};"));
4676 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4677 recordDecl(isExpansionInMainFile()), false,
4678 "-isystem/", M));
4679}
4680
4681TEST(Matcher, IsExpansionInSystemHeader) {
4682 FileContentMappings M;
4683 M.push_back(std::make_pair("/other", "class X {};"));
4684 EXPECT_TRUE(matchesConditionally(
4685 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4686 "-isystem/", M));
4687 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4688 recordDecl(isExpansionInSystemHeader()),
4689 false, "-I/", M));
4690 EXPECT_TRUE(notMatches("class X {};",
4691 recordDecl(isExpansionInSystemHeader())));
4692 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4693}
4694
4695TEST(Matcher, IsExpansionInFileMatching) {
4696 FileContentMappings M;
4697 M.push_back(std::make_pair("/foo", "class A {};"));
4698 M.push_back(std::make_pair("/bar", "class B {};"));
4699 EXPECT_TRUE(matchesConditionally(
4700 "#include <foo>\n"
4701 "#include <bar>\n"
4702 "class X {};",
4703 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4704 "-isystem/", M));
4705 EXPECT_TRUE(matchesConditionally(
4706 "#include <foo>\n"
4707 "#include <bar>\n"
4708 "class X {};",
4709 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4710 "-isystem/", M));
4711}
4712
4713#endif // LLVM_ON_WIN32
4714
Manuel Klimek4da21662012-07-06 05:48:52 +00004715} // end namespace ast_matchers
4716} // end namespace clang