blob: e424acdaacdc36f14c1d2c64b37a83f0c8afc070 [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()))))));
Edwin Vane742d9e72013-02-25 20:43:32 +0000378}
379
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000380TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000381 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000382 EXPECT_TRUE(notMatches("class X;", ClassX));
383 EXPECT_TRUE(notMatches("class X {};", ClassX));
384}
385
386TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000387 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000388 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
389 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
390}
391
392TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
393 EXPECT_TRUE(notMatches("template<typename T> class X { };"
394 "template<> class X<int> { int a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000395 classTemplateDecl(hasName("X"),
396 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000397}
398
399TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
400 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
401 "template<typename T> class X<T, int> { int a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000402 classTemplateDecl(hasName("X"),
403 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000404}
405
Daniel Jasper6a124492012-07-12 08:50:38 +0000406TEST(AllOf, AllOverloadsWork) {
407 const char Program[] =
Edwin Vane7f43fcf2013-02-12 13:55:40 +0000408 "struct T { };"
409 "int f(int, T*, int, int);"
410 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper6a124492012-07-12 08:50:38 +0000411 EXPECT_TRUE(matches(Program,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000412 callExpr(allOf(callee(functionDecl(hasName("f"))),
413 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper6a124492012-07-12 08:50:38 +0000414 EXPECT_TRUE(matches(Program,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000415 callExpr(allOf(callee(functionDecl(hasName("f"))),
416 hasArgument(0, declRefExpr(to(varDecl()))),
417 hasArgument(1, hasType(pointsTo(
418 recordDecl(hasName("T")))))))));
Edwin Vane7f43fcf2013-02-12 13:55:40 +0000419 EXPECT_TRUE(matches(Program,
420 callExpr(allOf(callee(functionDecl(hasName("f"))),
421 hasArgument(0, declRefExpr(to(varDecl()))),
422 hasArgument(1, hasType(pointsTo(
423 recordDecl(hasName("T"))))),
424 hasArgument(2, integerLiteral(equals(3)))))));
425 EXPECT_TRUE(matches(Program,
426 callExpr(allOf(callee(functionDecl(hasName("f"))),
427 hasArgument(0, declRefExpr(to(varDecl()))),
428 hasArgument(1, hasType(pointsTo(
429 recordDecl(hasName("T"))))),
430 hasArgument(2, integerLiteral(equals(3))),
431 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper6a124492012-07-12 08:50:38 +0000432}
433
Manuel Klimek4da21662012-07-06 05:48:52 +0000434TEST(DeclarationMatcher, MatchAnyOf) {
435 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000436 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000437 EXPECT_TRUE(
438 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
439 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
440 EXPECT_TRUE(
441 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
442 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
443
Daniel Jasperff2fcb82012-07-15 19:57:12 +0000444 DeclarationMatcher XOrYOrZOrU =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000445 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasperff2fcb82012-07-15 19:57:12 +0000446 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
447 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
448
Manuel Klimek4da21662012-07-06 05:48:52 +0000449 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000450 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
451 hasName("V")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000452 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
453 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
454 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
455 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
456 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
457 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
458}
459
460TEST(DeclarationMatcher, MatchHas) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000461 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000462 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
463 EXPECT_TRUE(matches("class X {};", HasClassX));
464
465 DeclarationMatcher YHasClassX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000466 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000467 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
468 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
469 EXPECT_TRUE(
470 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
471}
472
473TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
474 DeclarationMatcher Recursive =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000475 recordDecl(
476 has(recordDecl(
477 has(recordDecl(hasName("X"))),
478 has(recordDecl(hasName("Y"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000479 hasName("Z"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000480 has(recordDecl(
481 has(recordDecl(hasName("A"))),
482 has(recordDecl(hasName("B"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000483 hasName("C"))),
484 hasName("F"));
485
486 EXPECT_TRUE(matches(
487 "class F {"
488 " class Z {"
489 " class X {};"
490 " class Y {};"
491 " };"
492 " class C {"
493 " class A {};"
494 " class B {};"
495 " };"
496 "};", Recursive));
497
498 EXPECT_TRUE(matches(
499 "class F {"
500 " class Z {"
501 " class A {};"
502 " class X {};"
503 " class Y {};"
504 " };"
505 " class C {"
506 " class X {};"
507 " class A {};"
508 " class B {};"
509 " };"
510 "};", Recursive));
511
512 EXPECT_TRUE(matches(
513 "class O1 {"
514 " class O2 {"
515 " class F {"
516 " class Z {"
517 " class A {};"
518 " class X {};"
519 " class Y {};"
520 " };"
521 " class C {"
522 " class X {};"
523 " class A {};"
524 " class B {};"
525 " };"
526 " };"
527 " };"
528 "};", Recursive));
529}
530
531TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
532 DeclarationMatcher Recursive =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000533 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000534 anyOf(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000535 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000536 anyOf(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000537 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000538 hasName("X"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000539 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000540 hasName("Y"))),
541 hasName("Z")))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000542 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000543 anyOf(
544 hasName("C"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000545 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000546 hasName("A"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000547 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000548 hasName("B")))))),
549 hasName("F")));
550
551 EXPECT_TRUE(matches("class F {};", Recursive));
552 EXPECT_TRUE(matches("class Z {};", Recursive));
553 EXPECT_TRUE(matches("class C {};", Recursive));
554 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
555 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
556 EXPECT_TRUE(
557 matches("class O1 { class O2 {"
558 " class M { class N { class B {}; }; }; "
559 "}; };", Recursive));
560}
561
562TEST(DeclarationMatcher, MatchNot) {
563 DeclarationMatcher NotClassX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000564 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000565 isDerivedFrom("Y"),
Manuel Klimek4da21662012-07-06 05:48:52 +0000566 unless(hasName("X")));
567 EXPECT_TRUE(notMatches("", NotClassX));
568 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
569 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
570 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
571 EXPECT_TRUE(
572 notMatches("class Y {}; class Z {}; class X : public Y {};",
573 NotClassX));
574
575 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000576 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000577 hasName("X"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000578 has(recordDecl(hasName("Z"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000579 unless(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000580 has(recordDecl(hasName("Y")))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000581 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
582 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
583 ClassXHasNotClassY));
584}
585
586TEST(DeclarationMatcher, HasDescendant) {
587 DeclarationMatcher ZDescendantClassX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000588 recordDecl(
589 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000590 hasName("Z"));
591 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
592 EXPECT_TRUE(
593 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
594 EXPECT_TRUE(
595 matches("class Z { class A { class Y { class X {}; }; }; };",
596 ZDescendantClassX));
597 EXPECT_TRUE(
598 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
599 ZDescendantClassX));
600 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
601
602 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000603 recordDecl(
604 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000605 hasName("X"))),
606 hasName("Z"));
607 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
608 ZDescendantClassXHasClassY));
609 EXPECT_TRUE(
610 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
611 ZDescendantClassXHasClassY));
612 EXPECT_TRUE(notMatches(
613 "class Z {"
614 " class A {"
615 " class B {"
616 " class X {"
617 " class C {"
618 " class Y {};"
619 " };"
620 " };"
621 " }; "
622 " };"
623 "};", ZDescendantClassXHasClassY));
624
625 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000626 recordDecl(
627 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
628 hasName("X"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000629 hasName("Z"));
630 EXPECT_TRUE(
631 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
632 ZDescendantClassXDescendantClassY));
633 EXPECT_TRUE(matches(
634 "class Z {"
635 " class A {"
636 " class X {"
637 " class B {"
638 " class Y {};"
639 " };"
640 " class Y {};"
641 " };"
642 " };"
643 "};", ZDescendantClassXDescendantClassY));
644}
645
Daniel Jaspera267cf62012-10-29 10:14:44 +0000646// Implements a run method that returns whether BoundNodes contains a
647// Decl bound to Id that can be dynamically cast to T.
648// Optionally checks that the check succeeded a specific number of times.
649template <typename T>
650class VerifyIdIsBoundTo : public BoundNodesCallback {
651public:
652 // Create an object that checks that a node of type \c T was bound to \c Id.
653 // Does not check for a certain number of matches.
654 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
655 : Id(Id), ExpectedCount(-1), Count(0) {}
656
657 // Create an object that checks that a node of type \c T was bound to \c Id.
658 // Checks that there were exactly \c ExpectedCount matches.
659 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
660 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
661
662 // Create an object that checks that a node of type \c T was bound to \c Id.
663 // Checks that there was exactly one match with the name \c ExpectedName.
664 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimek374516c2013-03-14 16:33:21 +0000665 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
666 int ExpectedCount = 1)
667 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
668 ExpectedName(ExpectedName) {}
Daniel Jaspera267cf62012-10-29 10:14:44 +0000669
Stephen Hines651f13c2014-04-23 16:59:28 -0700670 void onEndOfTranslationUnit() override {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000671 if (ExpectedCount != -1)
672 EXPECT_EQ(ExpectedCount, Count);
673 if (!ExpectedName.empty())
674 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourned2bd5892013-11-07 22:30:32 +0000675 Count = 0;
676 Name.clear();
677 }
678
679 ~VerifyIdIsBoundTo() {
680 EXPECT_EQ(0, Count);
681 EXPECT_EQ("", Name);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000682 }
683
684 virtual bool run(const BoundNodes *Nodes) {
Peter Collingbourne3f0e0402013-11-06 00:27:07 +0000685 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jaspera267cf62012-10-29 10:14:44 +0000686 if (Nodes->getNodeAs<T>(Id)) {
687 ++Count;
688 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
689 Name = Named->getNameAsString();
690 } else if (const NestedNameSpecifier *NNS =
691 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
692 llvm::raw_string_ostream OS(Name);
693 NNS->print(OS, PrintingPolicy(LangOptions()));
694 }
Peter Collingbourne3f0e0402013-11-06 00:27:07 +0000695 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
696 EXPECT_NE(M.end(), I);
697 if (I != M.end())
698 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jaspera267cf62012-10-29 10:14:44 +0000699 return true;
700 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700701 EXPECT_TRUE(M.count(Id) == 0 ||
702 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000703 return false;
704 }
705
Daniel Jasper452abbc2012-10-29 10:48:25 +0000706 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
707 return run(Nodes);
708 }
709
Daniel Jaspera267cf62012-10-29 10:14:44 +0000710private:
711 const std::string Id;
712 const int ExpectedCount;
713 int Count;
714 const std::string ExpectedName;
715 std::string Name;
716};
717
718TEST(HasDescendant, MatchesDescendantTypes) {
719 EXPECT_TRUE(matches("void f() { int i = 3; }",
720 decl(hasDescendant(loc(builtinType())))));
721 EXPECT_TRUE(matches("void f() { int i = 3; }",
722 stmt(hasDescendant(builtinType()))));
723
724 EXPECT_TRUE(matches("void f() { int i = 3; }",
725 stmt(hasDescendant(loc(builtinType())))));
726 EXPECT_TRUE(matches("void f() { int i = 3; }",
727 stmt(hasDescendant(qualType(builtinType())))));
728
729 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
730 stmt(hasDescendant(isInteger()))));
731
732 EXPECT_TRUE(matchAndVerifyResultTrue(
733 "void f() { int a; float c; int d; int e; }",
734 functionDecl(forEachDescendant(
735 varDecl(hasDescendant(isInteger())).bind("x"))),
736 new VerifyIdIsBoundTo<Decl>("x", 3)));
737}
738
739TEST(HasDescendant, MatchesDescendantsOfTypes) {
740 EXPECT_TRUE(matches("void f() { int*** i; }",
741 qualType(hasDescendant(builtinType()))));
742 EXPECT_TRUE(matches("void f() { int*** i; }",
743 qualType(hasDescendant(
744 pointerType(pointee(builtinType()))))));
745 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikie5be093c2013-02-18 19:04:16 +0000746 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jaspera267cf62012-10-29 10:14:44 +0000747
748 EXPECT_TRUE(matchAndVerifyResultTrue(
749 "void f() { int*** i; }",
750 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
751 new VerifyIdIsBoundTo<Type>("x", 2)));
752}
753
754TEST(Has, MatchesChildrenOfTypes) {
755 EXPECT_TRUE(matches("int i;",
756 varDecl(hasName("i"), has(isInteger()))));
757 EXPECT_TRUE(notMatches("int** i;",
758 varDecl(hasName("i"), has(isInteger()))));
759 EXPECT_TRUE(matchAndVerifyResultTrue(
760 "int (*f)(float, int);",
761 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
762 new VerifyIdIsBoundTo<QualType>("x", 2)));
763}
764
765TEST(Has, MatchesChildTypes) {
766 EXPECT_TRUE(matches(
767 "int* i;",
768 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
769 EXPECT_TRUE(notMatches(
770 "int* i;",
771 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
772}
773
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000774TEST(Enum, DoesNotMatchClasses) {
775 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
776}
777
778TEST(Enum, MatchesEnums) {
779 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
780}
781
782TEST(EnumConstant, Matches) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000783 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000784 EXPECT_TRUE(matches("enum X{ A };", Matcher));
785 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
786 EXPECT_TRUE(notMatches("enum X {};", Matcher));
787}
788
Manuel Klimek4da21662012-07-06 05:48:52 +0000789TEST(StatementMatcher, Has) {
790 StatementMatcher HasVariableI =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000791 expr(hasType(pointsTo(recordDecl(hasName("X")))),
792 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000793
794 EXPECT_TRUE(matches(
795 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
796 EXPECT_TRUE(notMatches(
797 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
798}
799
800TEST(StatementMatcher, HasDescendant) {
801 StatementMatcher HasDescendantVariableI =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000802 expr(hasType(pointsTo(recordDecl(hasName("X")))),
803 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000804
805 EXPECT_TRUE(matches(
806 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
807 HasDescendantVariableI));
808 EXPECT_TRUE(notMatches(
809 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
810 HasDescendantVariableI));
811}
812
813TEST(TypeMatcher, MatchesClassType) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000814 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000815
816 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
817 EXPECT_TRUE(notMatches("class A {};", TypeA));
818
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000819 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000820
821 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
822 TypeDerivedFromA));
823 EXPECT_TRUE(notMatches("class A {};", TypeA));
824
825 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000826 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000827
828 EXPECT_TRUE(
829 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
830}
831
Manuel Klimek4da21662012-07-06 05:48:52 +0000832TEST(Matcher, BindMatchedNodes) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000833 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000834
835 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera7564432012-09-13 13:11:25 +0000836 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000837
838 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera7564432012-09-13 13:11:25 +0000839 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000840
841 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000842 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000843
844 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
845 TypeAHasClassB,
Daniel Jaspera7564432012-09-13 13:11:25 +0000846 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000847
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000848 StatementMatcher MethodX =
849 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek4da21662012-07-06 05:48:52 +0000850
851 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
852 MethodX,
Daniel Jaspera7564432012-09-13 13:11:25 +0000853 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000854}
855
856TEST(Matcher, BindTheSameNameInAlternatives) {
857 StatementMatcher matcher = anyOf(
858 binaryOperator(hasOperatorName("+"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000859 hasLHS(expr().bind("x")),
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000860 hasRHS(integerLiteral(equals(0)))),
861 binaryOperator(hasOperatorName("+"),
862 hasLHS(integerLiteral(equals(0))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000863 hasRHS(expr().bind("x"))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000864
865 EXPECT_TRUE(matchAndVerifyResultTrue(
866 // The first branch of the matcher binds x to 0 but then fails.
867 // The second branch binds x to f() and succeeds.
868 "int f() { return 0 + f(); }",
869 matcher,
Daniel Jaspera7564432012-09-13 13:11:25 +0000870 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000871}
872
Manuel Klimek66341c52012-08-30 19:41:06 +0000873TEST(Matcher, BindsIDForMemoizedResults) {
874 // Using the same matcher in two match expressions will make memoization
875 // kick in.
876 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
877 EXPECT_TRUE(matchAndVerifyResultTrue(
878 "class A { class B { class X {}; }; };",
879 DeclarationMatcher(anyOf(
880 recordDecl(hasName("A"), hasDescendant(ClassX)),
881 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera7564432012-09-13 13:11:25 +0000882 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimek66341c52012-08-30 19:41:06 +0000883}
884
Daniel Jasper189f2e42012-12-03 15:43:25 +0000885TEST(HasDeclaration, HasDeclarationOfEnumType) {
886 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
887 expr(hasType(pointsTo(
888 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
889}
890
Edwin Vaneb45083d2013-02-25 14:32:42 +0000891TEST(HasDeclaration, HasGetDeclTraitTest) {
892 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
893 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
894 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
895}
896
Edwin Vane52380602013-02-19 17:14:34 +0000897TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
898 EXPECT_TRUE(matches("typedef int X; X a;",
899 varDecl(hasName("a"),
900 hasType(typedefType(hasDeclaration(decl()))))));
901
902 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
903}
904
Edwin Vane3abf7782013-02-25 14:49:29 +0000905TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
906 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
907 varDecl(hasType(templateSpecializationType(
908 hasDeclaration(namedDecl(hasName("A"))))))));
909}
910
Manuel Klimek4da21662012-07-06 05:48:52 +0000911TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000912 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000913 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000914 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000915 EXPECT_TRUE(
916 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000917 expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000918 EXPECT_TRUE(
919 matches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000920 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000921}
922
923TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000924 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000925 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000926 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000927 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000928 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000929 EXPECT_TRUE(
930 matches("class X {}; void y() { X *x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000931 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000932}
933
934TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000935 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000936 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000937 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000938 EXPECT_TRUE(
939 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000940 expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000941}
942
943TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000944 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000945 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000946 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000947 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000948 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000949}
950
Manuel Klimek1a68afd2013-06-20 13:08:29 +0000951TEST(HasTypeLoc, MatchesDeclaratorDecls) {
952 EXPECT_TRUE(matches("int x;",
953 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
954
955 // Make sure we don't crash on implicit constructors.
956 EXPECT_TRUE(notMatches("class X {}; X x;",
957 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
958}
959
Manuel Klimek4da21662012-07-06 05:48:52 +0000960TEST(Matcher, Call) {
961 // FIXME: Do we want to overload Call() to directly take
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000962 // Matcher<Decl>, too?
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000963 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000964
965 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
966 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
967
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000968 StatementMatcher MethodOnY =
969 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000970
971 EXPECT_TRUE(
972 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
973 MethodOnY));
974 EXPECT_TRUE(
975 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
976 MethodOnY));
977 EXPECT_TRUE(
978 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
979 MethodOnY));
980 EXPECT_TRUE(
981 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
982 MethodOnY));
983 EXPECT_TRUE(
984 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
985 MethodOnY));
986
987 StatementMatcher MethodOnYPointer =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000988 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000989
990 EXPECT_TRUE(
991 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
992 MethodOnYPointer));
993 EXPECT_TRUE(
994 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
995 MethodOnYPointer));
996 EXPECT_TRUE(
997 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
998 MethodOnYPointer));
999 EXPECT_TRUE(
1000 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1001 MethodOnYPointer));
1002 EXPECT_TRUE(
1003 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1004 MethodOnYPointer));
1005}
1006
Daniel Jasper31f7c082012-10-01 13:40:41 +00001007TEST(Matcher, Lambda) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001008 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper31f7c082012-10-01 13:40:41 +00001009 lambdaExpr()));
1010}
1011
1012TEST(Matcher, ForRange) {
Daniel Jasper1a00fee2012-10-01 15:05:34 +00001013 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1014 "void f() { for (auto &a : as); }",
Daniel Jasper31f7c082012-10-01 13:40:41 +00001015 forRangeStmt()));
1016 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1017 forRangeStmt()));
1018}
1019
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001020TEST(Matcher, SubstNonTypeTemplateParm) {
1021 EXPECT_FALSE(matches("template<int N>\n"
1022 "struct A { static const int n = 0; };\n"
1023 "struct B : public A<42> {};",
1024 substNonTypeTemplateParmExpr()));
1025 EXPECT_TRUE(matches("template<int N>\n"
1026 "struct A { static const int n = N; };\n"
1027 "struct B : public A<42> {};",
1028 substNonTypeTemplateParmExpr()));
1029}
1030
Daniel Jasper31f7c082012-10-01 13:40:41 +00001031TEST(Matcher, UserDefinedLiteral) {
1032 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1033 " return i + 1;"
1034 "}"
1035 "char c = 'a'_inc;",
1036 userDefinedLiteral()));
1037}
1038
Daniel Jasperb54b7642012-09-20 14:12:57 +00001039TEST(Matcher, FlowControl) {
1040 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1041 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1042 continueStmt()));
1043 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1044 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1045 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1046}
1047
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001048TEST(HasType, MatchesAsString) {
1049 EXPECT_TRUE(
1050 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001051 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001052 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001053 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001054 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001055 fieldDecl(hasType(asString("ns::A")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001056 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
Stephen Hines651f13c2014-04-23 16:59:28 -07001057 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001058}
1059
Manuel Klimek4da21662012-07-06 05:48:52 +00001060TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001061 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001062 // Unary operator
1063 EXPECT_TRUE(matches("class Y { }; "
1064 "bool operator!(Y x) { return false; }; "
1065 "Y y; bool c = !y;", OpCall));
1066 // No match -- special operators like "new", "delete"
1067 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1068 // we need to figure out include paths in the test.
1069 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1070 // "class Y { }; "
1071 // "void *operator new(size_t size) { return 0; } "
1072 // "Y *y = new Y;", OpCall));
1073 EXPECT_TRUE(notMatches("class Y { }; "
1074 "void operator delete(void *p) { } "
1075 "void a() {Y *y = new Y; delete y;}", OpCall));
1076 // Binary operator
1077 EXPECT_TRUE(matches("class Y { }; "
1078 "bool operator&&(Y x, Y y) { return true; }; "
1079 "Y a; Y b; bool c = a && b;",
1080 OpCall));
1081 // No match -- normal operator, not an overloaded one.
1082 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1083 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1084}
1085
1086TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1087 StatementMatcher OpCallAndAnd =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001088 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek4da21662012-07-06 05:48:52 +00001089 EXPECT_TRUE(matches("class Y { }; "
1090 "bool operator&&(Y x, Y y) { return true; }; "
1091 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1092 StatementMatcher OpCallLessLess =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001093 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek4da21662012-07-06 05:48:52 +00001094 EXPECT_TRUE(notMatches("class Y { }; "
1095 "bool operator&&(Y x, Y y) { return true; }; "
1096 "Y a; Y b; bool c = a && b;",
1097 OpCallLessLess));
Edwin Vane6a19a972013-03-06 17:02:57 +00001098 DeclarationMatcher ClassWithOpStar =
1099 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1100 EXPECT_TRUE(matches("class Y { int operator*(); };",
1101 ClassWithOpStar));
1102 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1103 ClassWithOpStar)) ;
Manuel Klimek4da21662012-07-06 05:48:52 +00001104}
1105
Daniel Jasper278057f2012-11-15 03:29:05 +00001106TEST(Matcher, NestedOverloadedOperatorCalls) {
1107 EXPECT_TRUE(matchAndVerifyResultTrue(
1108 "class Y { }; "
1109 "Y& operator&&(Y& x, Y& y) { return x; }; "
1110 "Y a; Y b; Y c; Y d = a && b && c;",
1111 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1112 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1113 EXPECT_TRUE(matches(
1114 "class Y { }; "
1115 "Y& operator&&(Y& x, Y& y) { return x; }; "
1116 "Y a; Y b; Y c; Y d = a && b && c;",
1117 operatorCallExpr(hasParent(operatorCallExpr()))));
1118 EXPECT_TRUE(matches(
1119 "class Y { }; "
1120 "Y& operator&&(Y& x, Y& y) { return x; }; "
1121 "Y a; Y b; Y c; Y d = a && b && c;",
1122 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1123}
1124
Manuel Klimek4da21662012-07-06 05:48:52 +00001125TEST(Matcher, ThisPointerType) {
Manuel Klimek9f174082012-07-24 13:37:29 +00001126 StatementMatcher MethodOnY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001127 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001128
1129 EXPECT_TRUE(
1130 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1131 MethodOnY));
1132 EXPECT_TRUE(
1133 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1134 MethodOnY));
1135 EXPECT_TRUE(
1136 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1137 MethodOnY));
1138 EXPECT_TRUE(
1139 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1140 MethodOnY));
1141 EXPECT_TRUE(
1142 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1143 MethodOnY));
1144
1145 EXPECT_TRUE(matches(
1146 "class Y {"
1147 " public: virtual void x();"
1148 "};"
1149 "class X : public Y {"
1150 " public: virtual void x();"
1151 "};"
1152 "void z() { X *x; x->Y::x(); }", MethodOnY));
1153}
1154
1155TEST(Matcher, VariableUsage) {
1156 StatementMatcher Reference =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001157 declRefExpr(to(
1158 varDecl(hasInitializer(
1159 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001160
1161 EXPECT_TRUE(matches(
1162 "class Y {"
1163 " public:"
1164 " bool x() const;"
1165 "};"
1166 "void z(const Y &y) {"
1167 " bool b = y.x();"
1168 " if (b) {}"
1169 "}", Reference));
1170
1171 EXPECT_TRUE(notMatches(
1172 "class Y {"
1173 " public:"
1174 " bool x() const;"
1175 "};"
1176 "void z(const Y &y) {"
1177 " bool b = y.x();"
1178 "}", Reference));
1179}
1180
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001181TEST(Matcher, VarDecl_Storage) {
1182 auto M = varDecl(hasName("X"), hasLocalStorage());
1183 EXPECT_TRUE(matches("void f() { int X; }", M));
1184 EXPECT_TRUE(notMatches("int X;", M));
1185 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1186
1187 M = varDecl(hasName("X"), hasGlobalStorage());
1188 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1189 EXPECT_TRUE(matches("int X;", M));
1190 EXPECT_TRUE(matches("void f() { static int X; }", M));
1191}
1192
Manuel Klimek8cb9bf52012-12-04 14:42:08 +00001193TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper9bd28092012-07-30 05:03:25 +00001194 EXPECT_TRUE(matches(
1195 "void f(int i) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001196 varDecl(hasName("i"))));
Daniel Jasper9bd28092012-07-30 05:03:25 +00001197}
1198
Manuel Klimek4da21662012-07-06 05:48:52 +00001199TEST(Matcher, CalledVariable) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001200 StatementMatcher CallOnVariableY =
1201 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001202
1203 EXPECT_TRUE(matches(
1204 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1205 EXPECT_TRUE(matches(
1206 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1207 EXPECT_TRUE(matches(
1208 "class Y { public: void x(); };"
1209 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1210 EXPECT_TRUE(matches(
1211 "class Y { public: void x(); };"
1212 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1213 EXPECT_TRUE(notMatches(
1214 "class Y { public: void x(); };"
1215 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1216 CallOnVariableY));
1217}
1218
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001219TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1220 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1221 unaryExprOrTypeTraitExpr()));
1222 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1223 alignOfExpr(anything())));
1224 // FIXME: Uncomment once alignof is enabled.
1225 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1226 // unaryExprOrTypeTraitExpr()));
1227 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1228 // sizeOfExpr()));
1229}
1230
1231TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1232 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1233 hasArgumentOfType(asString("int")))));
1234 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1235 hasArgumentOfType(asString("float")))));
1236 EXPECT_TRUE(matches(
1237 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001238 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001239 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001240 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001241}
1242
Manuel Klimek4da21662012-07-06 05:48:52 +00001243TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001244 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001245}
1246
1247TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001248 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001249}
1250
1251TEST(MemberExpression, MatchesVariable) {
1252 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001253 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001254 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001255 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001256 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001257 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001258}
1259
1260TEST(MemberExpression, MatchesStaticVariable) {
1261 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001262 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001263 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001264 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001265 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001266 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001267}
1268
Daniel Jasper6a124492012-07-12 08:50:38 +00001269TEST(IsInteger, MatchesIntegers) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001270 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1271 EXPECT_TRUE(matches(
1272 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1273 callExpr(hasArgument(0, declRefExpr(
1274 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper6a124492012-07-12 08:50:38 +00001275}
1276
1277TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001278 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00001279 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001280 callExpr(hasArgument(0, declRefExpr(
1281 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper6a124492012-07-12 08:50:38 +00001282}
1283
Manuel Klimek4da21662012-07-06 05:48:52 +00001284TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1285 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001286 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001287 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001288 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001289 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001290 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001291}
1292
1293TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1294 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001295 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001296 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001297 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001298 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001299 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001300}
1301
1302TEST(IsArrow, MatchesMemberCallsViaArrow) {
1303 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001304 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001305 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001306 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001307 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001308 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001309}
1310
1311TEST(Callee, MatchesDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001312 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001313
1314 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1315 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1316}
1317
1318TEST(Callee, MatchesMemberExpressions) {
1319 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001320 callExpr(callee(memberExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001321 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001322 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001323}
1324
1325TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001326 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001327
1328 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1329 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1330
Stephen Hines651f13c2014-04-23 16:59:28 -07001331 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1332 llvm::Triple::Win32) {
1333 // FIXME: Make this work for MSVC.
1334 // Dependent contexts, but a non-dependent call.
1335 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1336 CallFunctionF));
1337 EXPECT_TRUE(
1338 matches("void f(); template <int N> struct S { void g() { f(); } };",
1339 CallFunctionF));
1340 }
Manuel Klimek4da21662012-07-06 05:48:52 +00001341
1342 // Depedent calls don't match.
1343 EXPECT_TRUE(
1344 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1345 CallFunctionF));
1346 EXPECT_TRUE(
1347 notMatches("void f(int);"
1348 "template <typename T> struct S { void g(T t) { f(t); } };",
1349 CallFunctionF));
1350}
1351
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001352TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1353 EXPECT_TRUE(
1354 matches("template <typename T> void f(T t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001355 functionTemplateDecl(hasName("f"))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001356}
1357
1358TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1359 EXPECT_TRUE(
1360 notMatches("void f(double d); void f(int t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001361 functionTemplateDecl(hasName("f"))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001362}
1363
1364TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1365 EXPECT_TRUE(
1366 notMatches("void g(); template <typename T> void f(T t) {}"
1367 "template <> void f(int t) { g(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001368 functionTemplateDecl(hasName("f"),
1369 hasDescendant(declRefExpr(to(
1370 functionDecl(hasName("g"))))))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001371}
1372
Manuel Klimek4da21662012-07-06 05:48:52 +00001373TEST(Matcher, Argument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001374 StatementMatcher CallArgumentY = callExpr(
1375 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001376
1377 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1378 EXPECT_TRUE(
1379 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1380 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1381
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001382 StatementMatcher WrongIndex = callExpr(
1383 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001384 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1385}
1386
1387TEST(Matcher, AnyArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001388 StatementMatcher CallArgumentY = callExpr(
1389 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001390 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1391 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1392 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1393}
1394
1395TEST(Matcher, ArgumentCount) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001396 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00001397
1398 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1399 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1400 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1401}
1402
Daniel Jasper36e29d62012-12-04 11:54:27 +00001403TEST(Matcher, ParameterCount) {
1404 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1405 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1406 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1407 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1408 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1409}
1410
Manuel Klimek4da21662012-07-06 05:48:52 +00001411TEST(Matcher, References) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001412 DeclarationMatcher ReferenceClassX = varDecl(
1413 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001414 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1415 ReferenceClassX));
1416 EXPECT_TRUE(
1417 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Han4b6730d2013-09-11 15:53:29 +00001418 // The match here is on the implicit copy constructor code for
1419 // class X, not on code 'X x = y'.
Manuel Klimek4da21662012-07-06 05:48:52 +00001420 EXPECT_TRUE(
Michael Han4b6730d2013-09-11 15:53:29 +00001421 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1422 EXPECT_TRUE(
1423 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek4da21662012-07-06 05:48:52 +00001424 EXPECT_TRUE(
1425 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1426}
1427
Edwin Vane6a19a972013-03-06 17:02:57 +00001428TEST(QualType, hasCanonicalType) {
1429 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1430 "int a;"
1431 "int_ref b = a;",
1432 varDecl(hasType(qualType(referenceType())))));
1433 EXPECT_TRUE(
1434 matches("typedef int &int_ref;"
1435 "int a;"
1436 "int_ref b = a;",
1437 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1438}
1439
Edwin Vane7b69cd02013-04-02 18:15:55 +00001440TEST(QualType, hasLocalQualifiers) {
1441 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1442 varDecl(hasType(hasLocalQualifiers()))));
1443 EXPECT_TRUE(matches("int *const j = nullptr;",
1444 varDecl(hasType(hasLocalQualifiers()))));
1445 EXPECT_TRUE(matches("int *volatile k;",
1446 varDecl(hasType(hasLocalQualifiers()))));
1447 EXPECT_TRUE(notMatches("int m;",
1448 varDecl(hasType(hasLocalQualifiers()))));
1449}
1450
Manuel Klimek4da21662012-07-06 05:48:52 +00001451TEST(HasParameter, CallsInnerMatcher) {
1452 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001453 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001454 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001455 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001456}
1457
1458TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1459 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001460 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001461}
1462
1463TEST(HasType, MatchesParameterVariableTypesStrictly) {
1464 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001465 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001466 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001467 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001468 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001469 methodDecl(hasParameter(0,
1470 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001471 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001472 methodDecl(hasParameter(0,
1473 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001474}
1475
1476TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1477 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001478 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001479 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001480 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001481}
1482
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001483TEST(Returns, MatchesReturnTypes) {
1484 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001485 functionDecl(returns(asString("int")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001486 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001487 functionDecl(returns(asString("float")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001488 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001489 functionDecl(returns(hasDeclaration(
1490 recordDecl(hasName("Y")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001491}
1492
Daniel Jasper8cc7efa2012-08-15 18:52:19 +00001493TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001494 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1495 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1496 functionDecl(isExternC())));
1497 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasper8cc7efa2012-08-15 18:52:19 +00001498}
1499
Manuel Klimek4da21662012-07-06 05:48:52 +00001500TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1501 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001502 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001503}
1504
1505TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1506 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001507 methodDecl(hasAnyParameter(hasType(pointsTo(
1508 recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001509}
1510
Stephen Hines651f13c2014-04-23 16:59:28 -07001511TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek4da21662012-07-06 05:48:52 +00001512 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001513 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001514 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001515 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001516}
1517
Daniel Jasper371f9392012-08-01 08:40:24 +00001518TEST(Matcher, MatchesClassTemplateSpecialization) {
1519 EXPECT_TRUE(matches("template<typename T> struct A {};"
1520 "template<> struct A<int> {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001521 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001522 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001523 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001524 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001525 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001526}
1527
Manuel Klimek1a68afd2013-06-20 13:08:29 +00001528TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1529 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1530 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1531}
1532
1533TEST(ParmVarDecl, MatchesParmVars) {
1534 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1535 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1536}
1537
Daniel Jasper371f9392012-08-01 08:40:24 +00001538TEST(Matcher, MatchesTypeTemplateArgument) {
1539 EXPECT_TRUE(matches(
1540 "template<typename T> struct B {};"
1541 "B<int> b;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001542 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper371f9392012-08-01 08:40:24 +00001543 asString("int"))))));
1544}
1545
1546TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1547 EXPECT_TRUE(matches(
1548 "struct B { int next; };"
1549 "template<int(B::*next_ptr)> struct A {};"
1550 "A<&B::next> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001551 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1552 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasperaaa8e452012-09-29 15:55:18 +00001553
1554 EXPECT_TRUE(notMatches(
1555 "template <typename T> struct A {};"
1556 "A<int> a;",
1557 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1558 refersToDeclaration(decl())))));
Stephen Hines651f13c2014-04-23 16:59:28 -07001559
1560 EXPECT_TRUE(matches(
1561 "struct B { int next; };"
1562 "template<int(B::*next_ptr)> struct A {};"
1563 "A<&B::next> a;",
1564 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1565 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1566
1567 EXPECT_TRUE(notMatches(
1568 "template <typename T> struct A {};"
1569 "A<int> a;",
1570 templateSpecializationType(hasAnyTemplateArgument(
1571 refersToDeclaration(decl())))));
Daniel Jasper371f9392012-08-01 08:40:24 +00001572}
1573
1574TEST(Matcher, MatchesSpecificArgument) {
1575 EXPECT_TRUE(matches(
1576 "template<typename T, typename U> class A {};"
1577 "A<bool, int> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001578 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper371f9392012-08-01 08:40:24 +00001579 1, refersToType(asString("int"))))));
1580 EXPECT_TRUE(notMatches(
1581 "template<typename T, typename U> class A {};"
1582 "A<int, bool> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001583 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper371f9392012-08-01 08:40:24 +00001584 1, refersToType(asString("int"))))));
Stephen Hines651f13c2014-04-23 16:59:28 -07001585
1586 EXPECT_TRUE(matches(
1587 "template<typename T, typename U> class A {};"
1588 "A<bool, int> a;",
1589 templateSpecializationType(hasTemplateArgument(
1590 1, refersToType(asString("int"))))));
1591 EXPECT_TRUE(notMatches(
1592 "template<typename T, typename U> class A {};"
1593 "A<int, bool> a;",
1594 templateSpecializationType(hasTemplateArgument(
1595 1, refersToType(asString("int"))))));
Daniel Jasper371f9392012-08-01 08:40:24 +00001596}
1597
Daniel Jasperf3197e92013-02-25 12:02:08 +00001598TEST(Matcher, MatchesAccessSpecDecls) {
1599 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1600 EXPECT_TRUE(
1601 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1602 EXPECT_TRUE(
1603 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1604 EXPECT_TRUE(
1605 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1606
1607 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1608}
1609
Edwin Vane5771a2f2013-04-09 20:46:36 +00001610TEST(Matcher, MatchesVirtualMethod) {
1611 EXPECT_TRUE(matches("class X { virtual int f(); };",
1612 methodDecl(isVirtual(), hasName("::X::f"))));
1613 EXPECT_TRUE(notMatches("class X { int f(); };",
1614 methodDecl(isVirtual())));
1615}
1616
Stephen Hines651f13c2014-04-23 16:59:28 -07001617TEST(Matcher, MatchesPureMethod) {
1618 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1619 methodDecl(isPure(), hasName("::X::f"))));
1620 EXPECT_TRUE(notMatches("class X { int f(); };",
1621 methodDecl(isPure())));
1622}
1623
Edwin Vane32a6ebc2013-05-09 17:00:17 +00001624TEST(Matcher, MatchesConstMethod) {
1625 EXPECT_TRUE(matches("struct A { void foo() const; };",
1626 methodDecl(isConst())));
1627 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1628 methodDecl(isConst())));
1629}
1630
Edwin Vane5771a2f2013-04-09 20:46:36 +00001631TEST(Matcher, MatchesOverridingMethod) {
1632 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1633 "class Y : public X { int f(); };",
1634 methodDecl(isOverride(), hasName("::Y::f"))));
1635 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1636 "class Y : public X { int f(); };",
1637 methodDecl(isOverride(), hasName("::X::f"))));
1638 EXPECT_TRUE(notMatches("class X { int f(); }; "
1639 "class Y : public X { int f(); };",
1640 methodDecl(isOverride())));
1641 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1642 methodDecl(isOverride())));
1643}
1644
Manuel Klimek4da21662012-07-06 05:48:52 +00001645TEST(Matcher, ConstructorCall) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001646 StatementMatcher Constructor = constructExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001647
1648 EXPECT_TRUE(
1649 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1650 EXPECT_TRUE(
1651 matches("class X { public: X(); }; void x() { X x = X(); }",
1652 Constructor));
1653 EXPECT_TRUE(
1654 matches("class X { public: X(int); }; void x() { X x = 0; }",
1655 Constructor));
1656 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1657}
1658
1659TEST(Matcher, ConstructorArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001660 StatementMatcher Constructor = constructExpr(
1661 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001662
1663 EXPECT_TRUE(
1664 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1665 Constructor));
1666 EXPECT_TRUE(
1667 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1668 Constructor));
1669 EXPECT_TRUE(
1670 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1671 Constructor));
1672 EXPECT_TRUE(
1673 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1674 Constructor));
1675
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001676 StatementMatcher WrongIndex = constructExpr(
1677 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001678 EXPECT_TRUE(
1679 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1680 WrongIndex));
1681}
1682
1683TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001684 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00001685
1686 EXPECT_TRUE(
1687 matches("class X { public: X(int); }; void x() { X x(0); }",
1688 Constructor1Arg));
1689 EXPECT_TRUE(
1690 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1691 Constructor1Arg));
1692 EXPECT_TRUE(
1693 matches("class X { public: X(int); }; void x() { X x = 0; }",
1694 Constructor1Arg));
1695 EXPECT_TRUE(
1696 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1697 Constructor1Arg));
1698}
1699
Stephen Hines651f13c2014-04-23 16:59:28 -07001700TEST(Matcher, ConstructorListInitialization) {
1701 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1702
1703 EXPECT_TRUE(
1704 matches("class X { public: X(int); }; void x() { X x{0}; }",
1705 ConstructorListInit));
1706 EXPECT_FALSE(
1707 matches("class X { public: X(int); }; void x() { X x(0); }",
1708 ConstructorListInit));
1709}
1710
Manuel Klimek70b9db92012-10-23 10:40:50 +00001711TEST(Matcher,ThisExpr) {
1712 EXPECT_TRUE(
1713 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1714 EXPECT_TRUE(
1715 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1716}
1717
Manuel Klimek4da21662012-07-06 05:48:52 +00001718TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001719 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001720
1721 std::string ClassString = "class string { public: string(); ~string(); }; ";
1722
1723 EXPECT_TRUE(
1724 matches(ClassString +
1725 "string GetStringByValue();"
1726 "void FunctionTakesString(string s);"
1727 "void run() { FunctionTakesString(GetStringByValue()); }",
1728 TempExpression));
1729
1730 EXPECT_TRUE(
1731 notMatches(ClassString +
1732 "string* GetStringPointer(); "
1733 "void FunctionTakesStringPtr(string* s);"
1734 "void run() {"
1735 " string* s = GetStringPointer();"
1736 " FunctionTakesStringPtr(GetStringPointer());"
1737 " FunctionTakesStringPtr(s);"
1738 "}",
1739 TempExpression));
1740
1741 EXPECT_TRUE(
1742 notMatches("class no_dtor {};"
1743 "no_dtor GetObjByValue();"
1744 "void ConsumeObj(no_dtor param);"
1745 "void run() { ConsumeObj(GetObjByValue()); }",
1746 TempExpression));
1747}
1748
Sam Panzere16acd32012-08-24 22:04:44 +00001749TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1750 std::string ClassString =
1751 "class string { public: string(); int length(); }; ";
1752
1753 EXPECT_TRUE(
1754 matches(ClassString +
1755 "string GetStringByValue();"
1756 "void FunctionTakesString(string s);"
1757 "void run() { FunctionTakesString(GetStringByValue()); }",
1758 materializeTemporaryExpr()));
1759
1760 EXPECT_TRUE(
1761 notMatches(ClassString +
1762 "string* GetStringPointer(); "
1763 "void FunctionTakesStringPtr(string* s);"
1764 "void run() {"
1765 " string* s = GetStringPointer();"
1766 " FunctionTakesStringPtr(GetStringPointer());"
1767 " FunctionTakesStringPtr(s);"
1768 "}",
1769 materializeTemporaryExpr()));
1770
1771 EXPECT_TRUE(
1772 notMatches(ClassString +
1773 "string GetStringByValue();"
1774 "void run() { int k = GetStringByValue().length(); }",
1775 materializeTemporaryExpr()));
1776
1777 EXPECT_TRUE(
1778 notMatches(ClassString +
1779 "string GetStringByValue();"
1780 "void run() { GetStringByValue(); }",
1781 materializeTemporaryExpr()));
1782}
1783
Manuel Klimek4da21662012-07-06 05:48:52 +00001784TEST(ConstructorDeclaration, SimpleCase) {
1785 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001786 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001787 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001788 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001789}
1790
1791TEST(ConstructorDeclaration, IsImplicit) {
1792 // This one doesn't match because the constructor is not added by the
1793 // compiler (it is not needed).
1794 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001795 constructorDecl(isImplicit())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001796 // The compiler added the implicit default constructor.
1797 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001798 constructorDecl(isImplicit())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001799 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001800 constructorDecl(unless(isImplicit()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001801 // The compiler added an implicit assignment operator.
1802 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1803 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001804}
1805
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001806TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1807 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001808 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001809}
1810
1811TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001812 EXPECT_TRUE(notMatches("class Foo {};",
1813 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001814}
1815
Manuel Klimek4da21662012-07-06 05:48:52 +00001816TEST(HasAnyConstructorInitializer, SimpleCase) {
1817 EXPECT_TRUE(notMatches(
1818 "class Foo { Foo() { } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001819 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001820 EXPECT_TRUE(matches(
1821 "class Foo {"
1822 " Foo() : foo_() { }"
1823 " int foo_;"
1824 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001825 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001826}
1827
1828TEST(HasAnyConstructorInitializer, ForField) {
1829 static const char Code[] =
1830 "class Baz { };"
1831 "class Foo {"
1832 " Foo() : foo_() { }"
1833 " Baz foo_;"
1834 " Baz bar_;"
1835 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001836 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1837 forField(hasType(recordDecl(hasName("Baz"))))))));
1838 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001839 forField(hasName("foo_"))))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001840 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1841 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001842}
1843
1844TEST(HasAnyConstructorInitializer, WithInitializer) {
1845 static const char Code[] =
1846 "class Foo {"
1847 " Foo() : foo_(0) { }"
1848 " int foo_;"
1849 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001850 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001851 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001852 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001853 withInitializer(integerLiteral(equals(1)))))));
1854}
1855
1856TEST(HasAnyConstructorInitializer, IsWritten) {
1857 static const char Code[] =
1858 "struct Bar { Bar(){} };"
1859 "class Foo {"
1860 " Foo() : foo_() { }"
1861 " Bar foo_;"
1862 " Bar bar_;"
1863 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001864 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001865 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001866 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001867 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001868 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001869 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1870}
1871
1872TEST(Matcher, NewExpression) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001873 StatementMatcher New = newExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001874
1875 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
1876 EXPECT_TRUE(
1877 matches("class X { public: X(); }; void x() { new X(); }", New));
1878 EXPECT_TRUE(
1879 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1880 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
1881}
1882
1883TEST(Matcher, NewExpressionArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001884 StatementMatcher New = constructExpr(
1885 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001886
1887 EXPECT_TRUE(
1888 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1889 New));
1890 EXPECT_TRUE(
1891 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1892 New));
1893 EXPECT_TRUE(
1894 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
1895 New));
1896
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001897 StatementMatcher WrongIndex = constructExpr(
1898 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001899 EXPECT_TRUE(
1900 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
1901 WrongIndex));
1902}
1903
1904TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001905 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00001906
1907 EXPECT_TRUE(
1908 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1909 EXPECT_TRUE(
1910 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
1911 New));
1912}
1913
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001914TEST(Matcher, DeleteExpression) {
1915 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001916 deleteExpr()));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001917}
1918
Manuel Klimek4da21662012-07-06 05:48:52 +00001919TEST(Matcher, DefaultArgument) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001920 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001921
1922 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
1923 EXPECT_TRUE(
1924 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
1925 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
1926}
1927
1928TEST(Matcher, StringLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001929 StatementMatcher Literal = stringLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00001930 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
1931 // wide string
1932 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
1933 // with escaped characters
1934 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
1935 // no matching -- though the data type is the same, there is no string literal
1936 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
1937}
1938
1939TEST(Matcher, CharacterLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001940 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00001941 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
1942 // wide character
1943 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
1944 // wide character, Hex encoded, NOT MATCHED!
1945 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
1946 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
1947}
1948
1949TEST(Matcher, IntegerLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001950 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00001951 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
1952 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
1953 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
1954 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
1955
1956 // Non-matching cases (character literals, float and double)
1957 EXPECT_TRUE(notMatches("int i = L'a';",
1958 HasIntLiteral)); // this is actually a character
1959 // literal cast to int
1960 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
1961 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
1962 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
1963}
1964
Daniel Jasperc5ae7172013-07-26 18:52:58 +00001965TEST(Matcher, FloatLiterals) {
1966 StatementMatcher HasFloatLiteral = floatLiteral();
1967 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
1968 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
1969 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
1970 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
1971 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
1972
1973 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
1974}
1975
Daniel Jasper31f7c082012-10-01 13:40:41 +00001976TEST(Matcher, NullPtrLiteral) {
1977 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
1978}
1979
Daniel Jasperb54b7642012-09-20 14:12:57 +00001980TEST(Matcher, AsmStatement) {
1981 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1982}
1983
Manuel Klimek4da21662012-07-06 05:48:52 +00001984TEST(Matcher, Conditions) {
1985 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
1986
1987 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
1988 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
1989 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
1990 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
1991 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
1992}
1993
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001994TEST(IfStmt, ChildTraversalMatchers) {
1995 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
1996 ifStmt(hasThen(boolLiteral(equals(true))))));
1997 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
1998 ifStmt(hasThen(boolLiteral(equals(true))))));
1999 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2000 ifStmt(hasElse(boolLiteral(equals(true))))));
2001 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2002 ifStmt(hasElse(boolLiteral(equals(true))))));
2003}
2004
Manuel Klimek4da21662012-07-06 05:48:52 +00002005TEST(MatchBinaryOperator, HasOperatorName) {
2006 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2007
2008 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2009 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2010}
2011
2012TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2013 StatementMatcher OperatorTrueFalse =
2014 binaryOperator(hasLHS(boolLiteral(equals(true))),
2015 hasRHS(boolLiteral(equals(false))));
2016
2017 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2018 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2019 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2020}
2021
2022TEST(MatchBinaryOperator, HasEitherOperand) {
2023 StatementMatcher HasOperand =
2024 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2025
2026 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2027 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2028 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2029}
2030
2031TEST(Matcher, BinaryOperatorTypes) {
2032 // Integration test that verifies the AST provides all binary operators in
2033 // a way we expect.
2034 // FIXME: Operator ','
2035 EXPECT_TRUE(
2036 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2037 EXPECT_TRUE(
2038 matches("bool b; bool c = (b = true);",
2039 binaryOperator(hasOperatorName("="))));
2040 EXPECT_TRUE(
2041 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2042 EXPECT_TRUE(
2043 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2044 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2045 EXPECT_TRUE(
2046 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2047 EXPECT_TRUE(
2048 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2049 EXPECT_TRUE(
2050 matches("int i = 1; int j = (i <<= 2);",
2051 binaryOperator(hasOperatorName("<<="))));
2052 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2053 EXPECT_TRUE(
2054 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2055 EXPECT_TRUE(
2056 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2057 EXPECT_TRUE(
2058 matches("int i = 1; int j = (i >>= 2);",
2059 binaryOperator(hasOperatorName(">>="))));
2060 EXPECT_TRUE(
2061 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2062 EXPECT_TRUE(
2063 matches("int i = 42; int j = (i ^= 42);",
2064 binaryOperator(hasOperatorName("^="))));
2065 EXPECT_TRUE(
2066 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2067 EXPECT_TRUE(
2068 matches("int i = 42; int j = (i %= 42);",
2069 binaryOperator(hasOperatorName("%="))));
2070 EXPECT_TRUE(
2071 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2072 EXPECT_TRUE(
2073 matches("bool b = true && false;",
2074 binaryOperator(hasOperatorName("&&"))));
2075 EXPECT_TRUE(
2076 matches("bool b = true; bool c = (b &= false);",
2077 binaryOperator(hasOperatorName("&="))));
2078 EXPECT_TRUE(
2079 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2080 EXPECT_TRUE(
2081 matches("bool b = true || false;",
2082 binaryOperator(hasOperatorName("||"))));
2083 EXPECT_TRUE(
2084 matches("bool b = true; bool c = (b |= false);",
2085 binaryOperator(hasOperatorName("|="))));
2086 EXPECT_TRUE(
2087 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2088 EXPECT_TRUE(
2089 matches("int i = 42; int j = (i *= 23);",
2090 binaryOperator(hasOperatorName("*="))));
2091 EXPECT_TRUE(
2092 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2093 EXPECT_TRUE(
2094 matches("int i = 42; int j = (i /= 23);",
2095 binaryOperator(hasOperatorName("/="))));
2096 EXPECT_TRUE(
2097 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2098 EXPECT_TRUE(
2099 matches("int i = 42; int j = (i += 23);",
2100 binaryOperator(hasOperatorName("+="))));
2101 EXPECT_TRUE(
2102 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2103 EXPECT_TRUE(
2104 matches("int i = 42; int j = (i -= 23);",
2105 binaryOperator(hasOperatorName("-="))));
2106 EXPECT_TRUE(
2107 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2108 binaryOperator(hasOperatorName("->*"))));
2109 EXPECT_TRUE(
2110 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2111 binaryOperator(hasOperatorName(".*"))));
2112
2113 // Member expressions as operators are not supported in matches.
2114 EXPECT_TRUE(
2115 notMatches("struct A { void x(A *a) { a->x(this); } };",
2116 binaryOperator(hasOperatorName("->"))));
2117
2118 // Initializer assignments are not represented as operator equals.
2119 EXPECT_TRUE(
2120 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2121
2122 // Array indexing is not represented as operator.
2123 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2124
2125 // Overloaded operators do not match at all.
2126 EXPECT_TRUE(notMatches(
2127 "struct A { bool operator&&(const A &a) const { return false; } };"
2128 "void x() { A a, b; a && b; }",
2129 binaryOperator()));
2130}
2131
2132TEST(MatchUnaryOperator, HasOperatorName) {
2133 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2134
2135 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2136 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2137}
2138
2139TEST(MatchUnaryOperator, HasUnaryOperand) {
2140 StatementMatcher OperatorOnFalse =
2141 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2142
2143 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2144 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2145}
2146
2147TEST(Matcher, UnaryOperatorTypes) {
2148 // Integration test that verifies the AST provides all unary operators in
2149 // a way we expect.
2150 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2151 EXPECT_TRUE(
2152 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2153 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2154 EXPECT_TRUE(
2155 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2156 EXPECT_TRUE(
2157 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2158 EXPECT_TRUE(
2159 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2160 EXPECT_TRUE(
2161 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2162 EXPECT_TRUE(
2163 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2164 EXPECT_TRUE(
2165 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2166 EXPECT_TRUE(
2167 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2168
2169 // We don't match conversion operators.
2170 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2171
2172 // Function calls are not represented as operator.
2173 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2174
2175 // Overloaded operators do not match at all.
2176 // FIXME: We probably want to add that.
2177 EXPECT_TRUE(notMatches(
2178 "struct A { bool operator!() const { return false; } };"
2179 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2180}
2181
2182TEST(Matcher, ConditionalOperator) {
2183 StatementMatcher Conditional = conditionalOperator(
2184 hasCondition(boolLiteral(equals(true))),
2185 hasTrueExpression(boolLiteral(equals(false))));
2186
2187 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2188 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2189 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2190
2191 StatementMatcher ConditionalFalse = conditionalOperator(
2192 hasFalseExpression(boolLiteral(equals(false))));
2193
2194 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2195 EXPECT_TRUE(
2196 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2197}
2198
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002199TEST(ArraySubscriptMatchers, ArraySubscripts) {
2200 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2201 arraySubscriptExpr()));
2202 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2203 arraySubscriptExpr()));
2204}
2205
2206TEST(ArraySubscriptMatchers, ArrayIndex) {
2207 EXPECT_TRUE(matches(
2208 "int i[2]; void f() { i[1] = 1; }",
2209 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2210 EXPECT_TRUE(matches(
2211 "int i[2]; void f() { 1[i] = 1; }",
2212 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2213 EXPECT_TRUE(notMatches(
2214 "int i[2]; void f() { i[1] = 1; }",
2215 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2216}
2217
2218TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2219 EXPECT_TRUE(matches(
2220 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002221 arraySubscriptExpr(hasBase(implicitCastExpr(
2222 hasSourceExpression(declRefExpr()))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002223}
2224
Manuel Klimek4da21662012-07-06 05:48:52 +00002225TEST(Matcher, HasNameSupportsNamespaces) {
2226 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002227 recordDecl(hasName("a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002228 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002229 recordDecl(hasName("::a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002230 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002231 recordDecl(hasName("b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002232 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002233 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002234 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002235 recordDecl(hasName("c::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002236 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002237 recordDecl(hasName("a::c::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002238 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002239 recordDecl(hasName("a::b::A"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002240 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002241 recordDecl(hasName("::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002242 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002243 recordDecl(hasName("::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002244 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002245 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002246 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002247 recordDecl(hasName("a+b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002248 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002249 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002250}
2251
2252TEST(Matcher, HasNameSupportsOuterClasses) {
2253 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002254 matches("class A { class B { class C; }; };",
2255 recordDecl(hasName("A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002256 EXPECT_TRUE(
2257 matches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002258 recordDecl(hasName("::A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002259 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002260 matches("class A { class B { class C; }; };",
2261 recordDecl(hasName("B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002262 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002263 matches("class A { class B { class C; }; };",
2264 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002265 EXPECT_TRUE(
2266 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002267 recordDecl(hasName("c::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002268 EXPECT_TRUE(
2269 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002270 recordDecl(hasName("A::c::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002271 EXPECT_TRUE(
2272 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002273 recordDecl(hasName("A::B::A"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002274 EXPECT_TRUE(
2275 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002276 recordDecl(hasName("::C"))));
2277 EXPECT_TRUE(
2278 notMatches("class A { class B { class C; }; };",
2279 recordDecl(hasName("::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002280 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002281 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002282 EXPECT_TRUE(
2283 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002284 recordDecl(hasName("A+B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002285}
2286
2287TEST(Matcher, IsDefinition) {
2288 DeclarationMatcher DefinitionOfClassA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002289 recordDecl(hasName("A"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002290 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2291 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2292
2293 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002294 varDecl(hasName("a"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002295 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2296 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2297
2298 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002299 methodDecl(hasName("a"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002300 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2301 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2302}
2303
2304TEST(Matcher, OfClass) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002305 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +00002306 ofClass(hasName("X")))));
2307
2308 EXPECT_TRUE(
2309 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2310 EXPECT_TRUE(
2311 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2312 Constructor));
2313 EXPECT_TRUE(
2314 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2315 Constructor));
2316}
2317
2318TEST(Matcher, VisitsTemplateInstantiations) {
2319 EXPECT_TRUE(matches(
2320 "class A { public: void x(); };"
2321 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002322 "void f() { B<A> b; b.y(); }",
2323 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002324
2325 EXPECT_TRUE(matches(
2326 "class A { public: void x(); };"
2327 "class C {"
2328 " public:"
2329 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2330 "};"
2331 "void f() {"
2332 " C::B<A> b; b.y();"
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002333 "}",
2334 recordDecl(hasName("C"),
2335 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002336}
2337
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002338TEST(Matcher, HandlesNullQualTypes) {
2339 // FIXME: Add a Type matcher so we can replace uses of this
2340 // variable with Type(True())
2341 const TypeMatcher AnyType = anything();
2342
2343 // We don't really care whether this matcher succeeds; we're testing that
2344 // it completes without crashing.
2345 EXPECT_TRUE(matches(
2346 "struct A { };"
2347 "template <typename T>"
2348 "void f(T t) {"
2349 " T local_t(t /* this becomes a null QualType in the AST */);"
2350 "}"
2351 "void g() {"
2352 " f(0);"
2353 "}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002354 expr(hasType(TypeMatcher(
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002355 anyOf(
2356 TypeMatcher(hasDeclaration(anything())),
2357 pointsTo(AnyType),
2358 references(AnyType)
2359 // Other QualType matchers should go here.
2360 ))))));
2361}
2362
Manuel Klimek4da21662012-07-06 05:48:52 +00002363// For testing AST_MATCHER_P().
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002364AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002365 // Make sure all special variables are used: node, match_finder,
2366 // bound_nodes_builder, and the parameter named 'AMatcher'.
2367 return AMatcher.matches(Node, Finder, Builder);
2368}
2369
2370TEST(AstMatcherPMacro, Works) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002371 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002372
2373 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002374 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002375
2376 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002377 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002378
2379 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002380 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002381}
2382
2383AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenef7eb022013-06-21 15:51:31 +00002384 polymorphicHas,
2385 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2386 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002387 return Finder->matchesChildOf(
Manuel Klimeka78d0d62012-09-05 12:12:07 +00002388 Node, AMatcher, Builder,
Manuel Klimek4da21662012-07-06 05:48:52 +00002389 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2390 ASTMatchFinder::BK_First);
2391}
2392
2393TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002394 DeclarationMatcher HasClassB =
2395 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek4da21662012-07-06 05:48:52 +00002396
2397 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002398 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002399
2400 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002401 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002402
2403 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002404 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002405
2406 StatementMatcher StatementHasClassB =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002407 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002408
2409 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2410}
2411
2412TEST(For, FindsForLoops) {
2413 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2414 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper1a00fee2012-10-01 15:05:34 +00002415 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2416 "void f() { for (auto &a : as); }",
Daniel Jasper31f7c082012-10-01 13:40:41 +00002417 forStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002418}
2419
Daniel Jasper6a124492012-07-12 08:50:38 +00002420TEST(For, ForLoopInternals) {
2421 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2422 forStmt(hasCondition(anything()))));
2423 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2424 forStmt(hasLoopInit(anything()))));
2425}
2426
Stephen Hines651f13c2014-04-23 16:59:28 -07002427TEST(For, ForRangeLoopInternals) {
2428 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2429 forRangeStmt(hasLoopVariable(anything()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002430 EXPECT_TRUE(matches(
2431 "void f(){ int a[] {1, 2}; for (int i : a); }",
2432 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Stephen Hines651f13c2014-04-23 16:59:28 -07002433}
2434
Daniel Jasper6a124492012-07-12 08:50:38 +00002435TEST(For, NegativeForLoopInternals) {
2436 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002437 forStmt(hasCondition(expr()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002438 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2439 forStmt(hasLoopInit(anything()))));
2440}
2441
Manuel Klimek4da21662012-07-06 05:48:52 +00002442TEST(For, ReportsNoFalsePositives) {
2443 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2444 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2445}
2446
2447TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002448 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2449 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2450 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002451}
2452
2453TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2454 // It's not a compound statement just because there's "{}" in the source
2455 // text. This is an AST search, not grep.
2456 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002457 compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002458 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002459 compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002460}
2461
Daniel Jasper6a124492012-07-12 08:50:38 +00002462TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002463 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002464 forStmt(hasBody(compoundStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002465 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002466 forStmt(hasBody(compoundStmt()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002467 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002468 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002469 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002470 doStmt(hasBody(compoundStmt()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002471 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2472 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002473}
2474
2475TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2476 // The simplest case: every compound statement is in a function
2477 // definition, and the function body itself must be a compound
2478 // statement.
2479 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002480 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002481}
2482
2483TEST(HasAnySubstatement, IsNotRecursive) {
2484 // It's really "has any immediate substatement".
2485 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002486 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002487}
2488
2489TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2490 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002491 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002492}
2493
2494TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2495 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002496 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002497}
2498
2499TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2500 EXPECT_TRUE(matches("void f() { }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002501 compoundStmt(statementCountIs(0))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002502 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002503 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002504}
2505
2506TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2507 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002508 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002509 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002510 compoundStmt(statementCountIs(0))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002511 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002512 compoundStmt(statementCountIs(2))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002513}
2514
2515TEST(StatementCountIs, WorksWithMultipleStatements) {
2516 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002517 compoundStmt(statementCountIs(3))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002518}
2519
2520TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2521 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002522 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002523 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002524 compoundStmt(statementCountIs(2))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002525 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002526 compoundStmt(statementCountIs(3))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002527 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002528 compoundStmt(statementCountIs(4))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002529}
2530
2531TEST(Member, WorksInSimplestCase) {
2532 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002533 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002534}
2535
2536TEST(Member, DoesNotMatchTheBaseExpression) {
2537 // Don't pick out the wrong part of the member expression, this should
2538 // be checking the member (name) only.
2539 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002540 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002541}
2542
2543TEST(Member, MatchesInMemberFunctionCall) {
2544 EXPECT_TRUE(matches("void f() {"
2545 " struct { void first() {}; } s;"
2546 " s.first();"
2547 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002548 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002549}
2550
Daniel Jasperc711af22012-10-23 15:46:39 +00002551TEST(Member, MatchesMember) {
2552 EXPECT_TRUE(matches(
2553 "struct A { int i; }; void f() { A a; a.i = 2; }",
2554 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2555 EXPECT_TRUE(notMatches(
2556 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2557 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2558}
2559
Daniel Jasperf3197e92013-02-25 12:02:08 +00002560TEST(Member, UnderstandsAccess) {
2561 EXPECT_TRUE(matches(
2562 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2563 EXPECT_TRUE(notMatches(
2564 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2565 EXPECT_TRUE(notMatches(
2566 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2567
2568 EXPECT_TRUE(notMatches(
2569 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2570 EXPECT_TRUE(notMatches(
2571 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2572 EXPECT_TRUE(matches(
2573 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2574
2575 EXPECT_TRUE(notMatches(
2576 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2577 EXPECT_TRUE(matches("class A { protected: int i; };",
2578 fieldDecl(isProtected(), hasName("i"))));
2579 EXPECT_TRUE(notMatches(
2580 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2581
2582 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2583 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2584 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2585 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2586}
2587
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002588TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper31f7c082012-10-01 13:40:41 +00002589 // Fails in C++11 mode
2590 EXPECT_TRUE(matchesConditionally(
2591 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2592 "class X { void *operator new(std::size_t); };",
2593 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002594
2595 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002596 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002597
Daniel Jasper31f7c082012-10-01 13:40:41 +00002598 // Fails in C++11 mode
2599 EXPECT_TRUE(matchesConditionally(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002600 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2601 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper31f7c082012-10-01 13:40:41 +00002602 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002603}
2604
Manuel Klimek4da21662012-07-06 05:48:52 +00002605TEST(HasObjectExpression, DoesNotMatchMember) {
2606 EXPECT_TRUE(notMatches(
2607 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002608 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002609}
2610
2611TEST(HasObjectExpression, MatchesBaseOfVariable) {
2612 EXPECT_TRUE(matches(
2613 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002614 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002615 EXPECT_TRUE(matches(
2616 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002617 memberExpr(hasObjectExpression(
2618 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002619}
2620
2621TEST(HasObjectExpression,
2622 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2623 EXPECT_TRUE(matches(
2624 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002625 memberExpr(hasObjectExpression(
2626 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002627 EXPECT_TRUE(matches(
2628 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002629 memberExpr(hasObjectExpression(
2630 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002631}
2632
2633TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002634 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2635 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2636 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2637 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002638}
2639
2640TEST(Field, MatchesField) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002641 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002642}
2643
2644TEST(IsConstQualified, MatchesConstInt) {
2645 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002646 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002647}
2648
2649TEST(IsConstQualified, MatchesConstPointer) {
2650 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002651 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002652}
2653
2654TEST(IsConstQualified, MatchesThroughTypedef) {
2655 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002656 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002657 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002658 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002659}
2660
2661TEST(IsConstQualified, DoesNotMatchInappropriately) {
2662 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002663 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002664 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002665 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002666}
2667
Sam Panzer089e5b32012-08-16 16:58:10 +00002668TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002669 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2670 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2671 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2672 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002673}
2674TEST(CastExpression, MatchesImplicitCasts) {
2675 // This test creates an implicit cast from int to char.
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002676 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002677 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002678 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002679}
2680
2681TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002682 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2683 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2684 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2685 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002686}
2687
Manuel Klimek4da21662012-07-06 05:48:52 +00002688TEST(ReinterpretCast, MatchesSimpleCase) {
2689 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002690 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002691}
2692
2693TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002694 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002695 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002696 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002697 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002698 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002699 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2700 "B b;"
2701 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002702 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002703}
2704
2705TEST(FunctionalCast, MatchesSimpleCase) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002706 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek4da21662012-07-06 05:48:52 +00002707 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002708 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002709}
2710
2711TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002712 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek4da21662012-07-06 05:48:52 +00002713 EXPECT_TRUE(
2714 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002715 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002716 EXPECT_TRUE(
2717 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002718 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002719}
2720
2721TEST(DynamicCast, MatchesSimpleCase) {
2722 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2723 "B b;"
2724 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002725 dynamicCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002726}
2727
2728TEST(StaticCast, MatchesSimpleCase) {
2729 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002730 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002731}
2732
2733TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002734 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002735 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002736 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002737 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002738 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002739 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2740 "B b;"
2741 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002742 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002743}
2744
Daniel Jaspere6d2a962012-09-18 13:36:17 +00002745TEST(CStyleCast, MatchesSimpleCase) {
2746 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2747}
2748
2749TEST(CStyleCast, DoesNotMatchOtherCasts) {
2750 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2751 "char q, *r = const_cast<char*>(&q);"
2752 "void* s = reinterpret_cast<char*>(&s);"
2753 "struct B { virtual ~B() {} }; struct D : B {};"
2754 "B b;"
2755 "D* t = dynamic_cast<D*>(&b);",
2756 cStyleCastExpr()));
2757}
2758
Manuel Klimek4da21662012-07-06 05:48:52 +00002759TEST(HasDestinationType, MatchesSimpleCase) {
2760 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002761 staticCastExpr(hasDestinationType(
2762 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002763}
2764
Sam Panzer089e5b32012-08-16 16:58:10 +00002765TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2766 // This test creates an implicit const cast.
2767 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002768 implicitCastExpr(
2769 hasImplicitDestinationType(isInteger()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002770 // This test creates an implicit array-to-pointer cast.
2771 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002772 implicitCastExpr(hasImplicitDestinationType(
2773 pointsTo(TypeMatcher(anything()))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002774}
2775
2776TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2777 // This test creates an implicit cast from int to char.
2778 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002779 implicitCastExpr(hasImplicitDestinationType(
2780 unless(anything())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002781 // This test creates an implicit array-to-pointer cast.
2782 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002783 implicitCastExpr(hasImplicitDestinationType(
2784 unless(anything())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002785}
2786
2787TEST(ImplicitCast, MatchesSimpleCase) {
2788 // This test creates an implicit const cast.
2789 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002790 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002791 // This test creates an implicit cast from int to char.
2792 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002793 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002794 // This test creates an implicit array-to-pointer cast.
2795 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002796 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002797}
2798
2799TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002800 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer089e5b32012-08-16 16:58:10 +00002801 // are present, and that it ignores explicit and paren casts.
2802
2803 // These two test cases have no casts.
2804 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002805 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002806 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002807 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002808
2809 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002810 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002811 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002812 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002813
2814 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002815 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002816}
2817
2818TEST(IgnoringImpCasts, MatchesImpCasts) {
2819 // This test checks that ignoringImpCasts matches when implicit casts are
2820 // present and its inner matcher alone does not match.
2821 // Note that this test creates an implicit const cast.
2822 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002823 varDecl(hasInitializer(ignoringImpCasts(
2824 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002825 // This test creates an implict cast from int to char.
2826 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002827 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002828 integerLiteral(equals(0)))))));
2829}
2830
2831TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2832 // These tests verify that ignoringImpCasts does not match if the inner
2833 // matcher does not match.
2834 // Note that the first test creates an implicit const cast.
2835 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002836 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002837 unless(anything()))))));
2838 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002839 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002840 unless(anything()))))));
2841
2842 // These tests verify that ignoringImplictCasts does not look through explicit
2843 // casts or parentheses.
2844 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002845 varDecl(hasInitializer(ignoringImpCasts(
2846 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002847 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002848 varDecl(hasInitializer(ignoringImpCasts(
2849 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002850 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002851 varDecl(hasInitializer(ignoringImpCasts(
2852 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002853 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002854 varDecl(hasInitializer(ignoringImpCasts(
2855 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002856}
2857
2858TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2859 // This test verifies that expressions that do not have implicit casts
2860 // still match the inner matcher.
2861 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002862 varDecl(hasInitializer(ignoringImpCasts(
2863 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002864}
2865
2866TEST(IgnoringParenCasts, MatchesParenCasts) {
2867 // This test checks that ignoringParenCasts matches when parentheses and/or
2868 // casts are present and its inner matcher alone does not match.
2869 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002870 varDecl(hasInitializer(ignoringParenCasts(
2871 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002872 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002873 varDecl(hasInitializer(ignoringParenCasts(
2874 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002875
2876 // This test creates an implict cast from int to char in addition to the
2877 // parentheses.
2878 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002879 varDecl(hasInitializer(ignoringParenCasts(
2880 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002881
2882 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002883 varDecl(hasInitializer(ignoringParenCasts(
2884 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002885 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002886 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002887 integerLiteral(equals(0)))))));
2888}
2889
2890TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
2891 // This test verifies that expressions that do not have any casts still match.
2892 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002893 varDecl(hasInitializer(ignoringParenCasts(
2894 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002895}
2896
2897TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
2898 // These tests verify that ignoringImpCasts does not match if the inner
2899 // matcher does not match.
2900 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002901 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002902 unless(anything()))))));
2903
2904 // This test creates an implicit cast from int to char in addition to the
2905 // parentheses.
2906 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002907 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002908 unless(anything()))))));
2909
2910 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002911 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002912 unless(anything()))))));
2913}
2914
2915TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
2916 // This test checks that ignoringParenAndImpCasts matches when
2917 // parentheses and/or implicit casts are present and its inner matcher alone
2918 // does not match.
2919 // Note that this test creates an implicit const cast.
2920 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002921 varDecl(hasInitializer(ignoringParenImpCasts(
2922 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002923 // This test creates an implicit cast from int to char.
2924 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002925 varDecl(hasInitializer(ignoringParenImpCasts(
2926 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002927}
2928
2929TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
2930 // This test verifies that expressions that do not have parentheses or
2931 // implicit casts still match.
2932 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002933 varDecl(hasInitializer(ignoringParenImpCasts(
2934 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002935 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002936 varDecl(hasInitializer(ignoringParenImpCasts(
2937 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002938}
2939
2940TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
2941 // These tests verify that ignoringParenImpCasts does not match if
2942 // the inner matcher does not match.
2943 // This test creates an implicit cast.
2944 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002945 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002946 unless(anything()))))));
2947 // These tests verify that ignoringParenAndImplictCasts does not look
2948 // through explicit casts.
2949 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002950 varDecl(hasInitializer(ignoringParenImpCasts(
2951 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002952 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002953 varDecl(hasInitializer(ignoringParenImpCasts(
2954 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002955 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002956 varDecl(hasInitializer(ignoringParenImpCasts(
2957 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002958}
2959
Manuel Klimek715c9562012-07-25 10:02:02 +00002960TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002961 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
2962 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002963 implicitCastExpr(
2964 hasSourceExpression(constructExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002965}
2966
Manuel Klimek715c9562012-07-25 10:02:02 +00002967TEST(HasSourceExpression, MatchesExplicitCasts) {
2968 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002969 explicitCastExpr(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002970 hasSourceExpression(hasDescendant(
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002971 expr(integerLiteral()))))));
Manuel Klimek715c9562012-07-25 10:02:02 +00002972}
2973
Manuel Klimek4da21662012-07-06 05:48:52 +00002974TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002975 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002976}
2977
2978TEST(Statement, MatchesCompoundStatments) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002979 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002980}
2981
2982TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002983 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002984}
2985
2986TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002987 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002988}
2989
Stephen Hines651f13c2014-04-23 16:59:28 -07002990TEST(ExprWithCleanups, MatchesExprWithCleanups) {
2991 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
2992 "const Foo f = Foo();",
2993 varDecl(hasInitializer(exprWithCleanups()))));
2994 EXPECT_FALSE(matches("struct Foo { };"
2995 "const Foo f = Foo();",
2996 varDecl(hasInitializer(exprWithCleanups()))));
2997}
2998
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002999TEST(InitListExpression, MatchesInitListExpression) {
3000 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3001 initListExpr(hasType(asString("int [2]")))));
3002 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003003 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003004}
3005
3006TEST(UsingDeclaration, MatchesUsingDeclarations) {
3007 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3008 usingDecl()));
3009}
3010
3011TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3012 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3013 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3014}
3015
3016TEST(UsingDeclaration, MatchesSpecificTarget) {
3017 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3018 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003019 hasTargetDecl(functionDecl())))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003020 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3021 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003022 hasTargetDecl(functionDecl())))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003023}
3024
3025TEST(UsingDeclaration, ThroughUsingDeclaration) {
3026 EXPECT_TRUE(matches(
3027 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003028 declRefExpr(throughUsingDecl(anything()))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003029 EXPECT_TRUE(notMatches(
3030 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003031 declRefExpr(throughUsingDecl(anything()))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003032}
3033
Sam Panzer425f41b2012-08-16 17:20:59 +00003034TEST(SingleDecl, IsSingleDecl) {
3035 StatementMatcher SingleDeclStmt =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003036 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003037 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3038 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3039 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3040 SingleDeclStmt));
3041}
3042
3043TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003044 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzer425f41b2012-08-16 17:20:59 +00003045
3046 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003047 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003048 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003049 declStmt(containsDeclaration(0, MatchesInit),
3050 containsDeclaration(1, MatchesInit))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003051 unsigned WrongIndex = 42;
3052 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003053 declStmt(containsDeclaration(WrongIndex,
Sam Panzer425f41b2012-08-16 17:20:59 +00003054 MatchesInit))));
3055}
3056
3057TEST(DeclCount, DeclCountIsCorrect) {
3058 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003059 declStmt(declCountIs(2))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003060 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003061 declStmt(declCountIs(3))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003062 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003063 declStmt(declCountIs(3))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003064}
3065
Manuel Klimek4da21662012-07-06 05:48:52 +00003066TEST(While, MatchesWhileLoops) {
3067 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3068 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3069 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3070}
3071
3072TEST(Do, MatchesDoLoops) {
3073 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3074 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3075}
3076
3077TEST(Do, DoesNotMatchWhileLoops) {
3078 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3079}
3080
3081TEST(SwitchCase, MatchesCase) {
3082 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3083 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3084 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3085 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3086}
3087
Daniel Jasperb54b7642012-09-20 14:12:57 +00003088TEST(SwitchCase, MatchesSwitch) {
3089 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3090 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3091 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3092 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3093}
3094
Peter Collingbourneacf02712013-05-10 11:52:02 +00003095TEST(SwitchCase, MatchesEachCase) {
3096 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3097 switchStmt(forEachSwitchCase(caseStmt()))));
3098 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3099 switchStmt(forEachSwitchCase(caseStmt()))));
3100 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3101 switchStmt(forEachSwitchCase(caseStmt()))));
3102 EXPECT_TRUE(notMatches(
3103 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3104 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3105 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3106 switchStmt(forEachSwitchCase(
3107 caseStmt(hasCaseConstant(integerLiteral()))))));
3108 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3109 switchStmt(forEachSwitchCase(
3110 caseStmt(hasCaseConstant(integerLiteral()))))));
3111 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3112 switchStmt(forEachSwitchCase(
3113 caseStmt(hasCaseConstant(integerLiteral()))))));
3114 EXPECT_TRUE(matchAndVerifyResultTrue(
3115 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3116 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3117 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3118}
3119
Manuel Klimek06963012013-07-19 11:50:54 +00003120TEST(ForEachConstructorInitializer, MatchesInitializers) {
3121 EXPECT_TRUE(matches(
3122 "struct X { X() : i(42), j(42) {} int i, j; };",
3123 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3124}
3125
Daniel Jasperb54b7642012-09-20 14:12:57 +00003126TEST(ExceptionHandling, SimpleCases) {
3127 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3128 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3129 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3130 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3131 throwExpr()));
3132 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3133 throwExpr()));
3134}
3135
Manuel Klimek4da21662012-07-06 05:48:52 +00003136TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3137 EXPECT_TRUE(notMatches(
3138 "void x() { if(true) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003139 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003140 EXPECT_TRUE(notMatches(
3141 "void x() { int x; if((x = 42)) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003142 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003143}
3144
3145TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3146 EXPECT_TRUE(matches(
3147 "void x() { if(int* a = 0) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003148 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003149}
3150
3151TEST(ForEach, BindsOneNode) {
3152 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003153 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003154 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003155}
3156
3157TEST(ForEach, BindsMultipleNodes) {
3158 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003159 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003160 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003161}
3162
3163TEST(ForEach, BindsRecursiveCombinations) {
3164 EXPECT_TRUE(matchAndVerifyResultTrue(
3165 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003166 recordDecl(hasName("C"),
3167 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003168 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003169}
3170
3171TEST(ForEachDescendant, BindsOneNode) {
3172 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003173 recordDecl(hasName("C"),
3174 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003175 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003176}
3177
Daniel Jasper5f684e92012-11-16 18:39:22 +00003178TEST(ForEachDescendant, NestedForEachDescendant) {
3179 DeclarationMatcher m = recordDecl(
3180 isDefinition(), decl().bind("x"), hasName("C"));
3181 EXPECT_TRUE(matchAndVerifyResultTrue(
3182 "class A { class B { class C {}; }; };",
3183 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3184 new VerifyIdIsBoundTo<Decl>("x", "C")));
3185
Manuel Klimek054d0492013-06-19 15:42:45 +00003186 // Check that a partial match of 'm' that binds 'x' in the
3187 // first part of anyOf(m, anything()) will not overwrite the
3188 // binding created by the earlier binding in the hasDescendant.
3189 EXPECT_TRUE(matchAndVerifyResultTrue(
3190 "class A { class B { class C {}; }; };",
3191 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3192 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper5f684e92012-11-16 18:39:22 +00003193}
3194
Manuel Klimek4da21662012-07-06 05:48:52 +00003195TEST(ForEachDescendant, BindsMultipleNodes) {
3196 EXPECT_TRUE(matchAndVerifyResultTrue(
3197 "class C { class D { int x; int y; }; "
3198 " class E { class F { int y; int z; }; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003199 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003200 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003201}
3202
3203TEST(ForEachDescendant, BindsRecursiveCombinations) {
3204 EXPECT_TRUE(matchAndVerifyResultTrue(
3205 "class C { class D { "
3206 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003207 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3208 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003209 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003210}
3211
Manuel Klimek054d0492013-06-19 15:42:45 +00003212TEST(ForEachDescendant, BindsCombinations) {
3213 EXPECT_TRUE(matchAndVerifyResultTrue(
3214 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3215 "(true) {} }",
3216 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3217 forEachDescendant(whileStmt().bind("while"))),
3218 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3219}
3220
3221TEST(Has, DoesNotDeleteBindings) {
3222 EXPECT_TRUE(matchAndVerifyResultTrue(
3223 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3224 new VerifyIdIsBoundTo<Decl>("x", 1)));
3225}
3226
3227TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3228 // Those matchers cover all the cases where an inner matcher is called
3229 // and there is not a 1:1 relationship between the match of the outer
3230 // matcher and the match of the inner matcher.
3231 // The pattern to look for is:
3232 // ... return InnerMatcher.matches(...); ...
3233 // In which case no special handling is needed.
3234 //
3235 // On the other hand, if there are multiple alternative matches
3236 // (for example forEach*) or matches might be discarded (for example has*)
3237 // the implementation must make sure that the discarded matches do not
3238 // affect the bindings.
3239 // When new such matchers are added, add a test here that:
3240 // - matches a simple node, and binds it as the first thing in the matcher:
3241 // recordDecl(decl().bind("x"), hasName("X")))
3242 // - uses the matcher under test afterwards in a way that not the first
3243 // alternative is matched; for anyOf, that means the first branch
3244 // would need to return false; for hasAncestor, it means that not
3245 // the direct parent matches the inner matcher.
3246
3247 EXPECT_TRUE(matchAndVerifyResultTrue(
3248 "class X { int y; };",
3249 recordDecl(
3250 recordDecl().bind("x"), hasName("::X"),
3251 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3252 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3253 EXPECT_TRUE(matchAndVerifyResultTrue(
3254 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3255 anyOf(unless(anything()), anything())),
3256 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3257 EXPECT_TRUE(matchAndVerifyResultTrue(
3258 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3259 classTemplateSpecializationDecl(
3260 decl().bind("x"),
3261 hasAnyTemplateArgument(refersToType(asString("int")))),
3262 new VerifyIdIsBoundTo<Decl>("x", 1)));
3263 EXPECT_TRUE(matchAndVerifyResultTrue(
3264 "class X { void f(); void g(); };",
3265 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3266 new VerifyIdIsBoundTo<Decl>("x", 1)));
3267 EXPECT_TRUE(matchAndVerifyResultTrue(
3268 "class X { X() : a(1), b(2) {} double a; int b; };",
3269 recordDecl(decl().bind("x"),
3270 has(constructorDecl(
3271 hasAnyConstructorInitializer(forField(hasName("b")))))),
3272 new VerifyIdIsBoundTo<Decl>("x", 1)));
3273 EXPECT_TRUE(matchAndVerifyResultTrue(
3274 "void x(int, int) { x(0, 42); }",
3275 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3276 new VerifyIdIsBoundTo<Expr>("x", 1)));
3277 EXPECT_TRUE(matchAndVerifyResultTrue(
3278 "void x(int, int y) {}",
3279 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3280 new VerifyIdIsBoundTo<Decl>("x", 1)));
3281 EXPECT_TRUE(matchAndVerifyResultTrue(
3282 "void x() { return; if (true) {} }",
3283 functionDecl(decl().bind("x"),
3284 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3285 new VerifyIdIsBoundTo<Decl>("x", 1)));
3286 EXPECT_TRUE(matchAndVerifyResultTrue(
3287 "namespace X { void b(int); void b(); }"
3288 "using X::b;",
3289 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3290 functionDecl(parameterCountIs(1))))),
3291 new VerifyIdIsBoundTo<Decl>("x", 1)));
3292 EXPECT_TRUE(matchAndVerifyResultTrue(
3293 "class A{}; class B{}; class C : B, A {};",
3294 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3295 new VerifyIdIsBoundTo<Decl>("x", 1)));
3296 EXPECT_TRUE(matchAndVerifyResultTrue(
3297 "class A{}; typedef A B; typedef A C; typedef A D;"
3298 "class E : A {};",
3299 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3300 new VerifyIdIsBoundTo<Decl>("x", 1)));
3301 EXPECT_TRUE(matchAndVerifyResultTrue(
3302 "class A { class B { void f() {} }; };",
3303 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3304 new VerifyIdIsBoundTo<Decl>("x", 1)));
3305 EXPECT_TRUE(matchAndVerifyResultTrue(
3306 "template <typename T> struct A { struct B {"
3307 " void f() { if(true) {} }"
3308 "}; };"
3309 "void t() { A<int>::B b; b.f(); }",
3310 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3311 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3312 EXPECT_TRUE(matchAndVerifyResultTrue(
3313 "class A {};",
3314 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3315 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimek06963012013-07-19 11:50:54 +00003316 EXPECT_TRUE(matchAndVerifyResultTrue(
3317 "class A { A() : s(), i(42) {} const char *s; int i; };",
3318 constructorDecl(hasName("::A::A"), decl().bind("x"),
3319 forEachConstructorInitializer(forField(hasName("i")))),
3320 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimek054d0492013-06-19 15:42:45 +00003321}
3322
Daniel Jasper11c98772012-11-11 22:14:55 +00003323TEST(ForEachDescendant, BindsCorrectNodes) {
3324 EXPECT_TRUE(matchAndVerifyResultTrue(
3325 "class C { void f(); int i; };",
3326 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3327 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3328 EXPECT_TRUE(matchAndVerifyResultTrue(
3329 "class C { void f() {} int i; };",
3330 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3331 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3332}
3333
Manuel Klimek152ea0e2013-02-04 10:59:20 +00003334TEST(FindAll, BindsNodeOnMatch) {
3335 EXPECT_TRUE(matchAndVerifyResultTrue(
3336 "class A {};",
3337 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3338 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3339}
3340
3341TEST(FindAll, BindsDescendantNodeOnMatch) {
3342 EXPECT_TRUE(matchAndVerifyResultTrue(
3343 "class A { int a; int b; };",
3344 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3345 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3346}
3347
3348TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3349 EXPECT_TRUE(matchAndVerifyResultTrue(
3350 "class A { int a; int b; };",
3351 recordDecl(hasName("::A"),
3352 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3353 fieldDecl().bind("v"))))),
3354 new VerifyIdIsBoundTo<Decl>("v", 3)));
3355
3356 EXPECT_TRUE(matchAndVerifyResultTrue(
3357 "class A { class B {}; class C {}; };",
3358 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3359 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3360}
3361
Manuel Klimek73876732013-02-04 09:42:38 +00003362TEST(EachOf, TriggersForEachMatch) {
3363 EXPECT_TRUE(matchAndVerifyResultTrue(
3364 "class A { int a; int b; };",
3365 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3366 has(fieldDecl(hasName("b")).bind("v")))),
3367 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3368}
3369
3370TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3371 EXPECT_TRUE(matchAndVerifyResultTrue(
3372 "class A { int a; int c; };",
3373 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3374 has(fieldDecl(hasName("b")).bind("v")))),
3375 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3376 EXPECT_TRUE(matchAndVerifyResultTrue(
3377 "class A { int c; int b; };",
3378 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3379 has(fieldDecl(hasName("b")).bind("v")))),
3380 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3381 EXPECT_TRUE(notMatches(
3382 "class A { int c; int d; };",
3383 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3384 has(fieldDecl(hasName("b")).bind("v"))))));
3385}
Manuel Klimek4da21662012-07-06 05:48:52 +00003386
3387TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3388 // Make sure that we can both match the class by name (::X) and by the type
3389 // the template was instantiated with (via a field).
3390
3391 EXPECT_TRUE(matches(
3392 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003393 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003394
3395 EXPECT_TRUE(matches(
3396 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003397 recordDecl(isTemplateInstantiation(), hasDescendant(
3398 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003399}
3400
3401TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3402 EXPECT_TRUE(matches(
3403 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003404 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek4da21662012-07-06 05:48:52 +00003405 isTemplateInstantiation())));
3406}
3407
3408TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3409 EXPECT_TRUE(matches(
3410 "template <typename T> class X { T t; }; class A {};"
3411 "template class X<A>;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003412 recordDecl(isTemplateInstantiation(), hasDescendant(
3413 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003414}
3415
3416TEST(IsTemplateInstantiation,
3417 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3418 EXPECT_TRUE(matches(
3419 "template <typename T> class X {};"
3420 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003421 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003422}
3423
3424TEST(IsTemplateInstantiation,
3425 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3426 EXPECT_TRUE(matches(
3427 "class A {};"
3428 "class X {"
3429 " template <typename U> class Y { U u; };"
3430 " Y<A> y;"
3431 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003432 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003433}
3434
3435TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3436 // FIXME: Figure out whether this makes sense. It doesn't affect the
3437 // normal use case as long as the uppermost instantiation always is marked
3438 // as template instantiation, but it might be confusing as a predicate.
3439 EXPECT_TRUE(matches(
3440 "class A {};"
3441 "template <typename T> class X {"
3442 " template <typename U> class Y { U u; };"
3443 " Y<T> y;"
3444 "}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003445 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003446}
3447
3448TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3449 EXPECT_TRUE(notMatches(
3450 "template <typename T> class X {}; class A {};"
3451 "template <> class X<A> {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003452 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003453}
3454
3455TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3456 EXPECT_TRUE(notMatches(
3457 "class A {}; class Y { A a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003458 recordDecl(isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003459}
3460
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003461TEST(IsExplicitTemplateSpecialization,
3462 DoesNotMatchPrimaryTemplate) {
3463 EXPECT_TRUE(notMatches(
3464 "template <typename T> class X {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003465 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003466 EXPECT_TRUE(notMatches(
3467 "template <typename T> void f(T t);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003468 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003469}
3470
3471TEST(IsExplicitTemplateSpecialization,
3472 DoesNotMatchExplicitTemplateInstantiations) {
3473 EXPECT_TRUE(notMatches(
3474 "template <typename T> class X {};"
3475 "template class X<int>; extern template class X<long>;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003476 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003477 EXPECT_TRUE(notMatches(
3478 "template <typename T> void f(T t) {}"
3479 "template void f(int t); extern template void f(long t);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003480 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003481}
3482
3483TEST(IsExplicitTemplateSpecialization,
3484 DoesNotMatchImplicitTemplateInstantiations) {
3485 EXPECT_TRUE(notMatches(
3486 "template <typename T> class X {}; X<int> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003487 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003488 EXPECT_TRUE(notMatches(
3489 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003490 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003491}
3492
3493TEST(IsExplicitTemplateSpecialization,
3494 MatchesExplicitTemplateSpecializations) {
3495 EXPECT_TRUE(matches(
3496 "template <typename T> class X {};"
3497 "template<> class X<int> {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003498 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003499 EXPECT_TRUE(matches(
3500 "template <typename T> void f(T t) {}"
3501 "template<> void f(int t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003502 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003503}
3504
Manuel Klimek579b1202012-09-07 09:26:10 +00003505TEST(HasAncenstor, MatchesDeclarationAncestors) {
3506 EXPECT_TRUE(matches(
3507 "class A { class B { class C {}; }; };",
3508 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3509}
3510
3511TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3512 EXPECT_TRUE(notMatches(
3513 "class A { class B { class C {}; }; };",
3514 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3515}
3516
3517TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3518 EXPECT_TRUE(matches(
3519 "class A { class B { void f() { C c; } class C {}; }; };",
3520 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3521 hasAncestor(recordDecl(hasName("A"))))))));
3522}
3523
3524TEST(HasAncenstor, MatchesStatementAncestors) {
3525 EXPECT_TRUE(matches(
3526 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003527 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek579b1202012-09-07 09:26:10 +00003528}
3529
3530TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3531 EXPECT_TRUE(matches(
3532 "void f() { if (true) { int x = 42; } }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003533 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek579b1202012-09-07 09:26:10 +00003534}
3535
3536TEST(HasAncestor, BindsRecursiveCombinations) {
3537 EXPECT_TRUE(matchAndVerifyResultTrue(
3538 "class C { class D { class E { class F { int y; }; }; }; };",
3539 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003540 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek579b1202012-09-07 09:26:10 +00003541}
3542
3543TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3544 EXPECT_TRUE(matchAndVerifyResultTrue(
3545 "class C { class D { class E { class F { int y; }; }; }; };",
3546 fieldDecl(hasAncestor(
3547 decl(
3548 hasDescendant(recordDecl(isDefinition(),
3549 hasAncestor(recordDecl())))
3550 ).bind("d")
3551 )),
Daniel Jaspera7564432012-09-13 13:11:25 +00003552 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek579b1202012-09-07 09:26:10 +00003553}
3554
Manuel Klimek374516c2013-03-14 16:33:21 +00003555TEST(HasAncestor, MatchesClosestAncestor) {
3556 EXPECT_TRUE(matchAndVerifyResultTrue(
3557 "template <typename T> struct C {"
3558 " void f(int) {"
3559 " struct I { void g(T) { int x; } } i; i.g(42);"
3560 " }"
3561 "};"
3562 "template struct C<int>;",
3563 varDecl(hasName("x"),
3564 hasAncestor(functionDecl(hasParameter(
3565 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3566 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3567}
3568
Manuel Klimek579b1202012-09-07 09:26:10 +00003569TEST(HasAncestor, MatchesInTemplateInstantiations) {
3570 EXPECT_TRUE(matches(
3571 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3572 "A<int>::B::C a;",
3573 fieldDecl(hasType(asString("int")),
3574 hasAncestor(recordDecl(hasName("A"))))));
3575}
3576
3577TEST(HasAncestor, MatchesInImplicitCode) {
3578 EXPECT_TRUE(matches(
3579 "struct X {}; struct A { A() {} X x; };",
3580 constructorDecl(
3581 hasAnyConstructorInitializer(withInitializer(expr(
3582 hasAncestor(recordDecl(hasName("A")))))))));
3583}
3584
Daniel Jasperc99a3ad2012-10-22 16:26:51 +00003585TEST(HasParent, MatchesOnlyParent) {
3586 EXPECT_TRUE(matches(
3587 "void f() { if (true) { int x = 42; } }",
3588 compoundStmt(hasParent(ifStmt()))));
3589 EXPECT_TRUE(notMatches(
3590 "void f() { for (;;) { int x = 42; } }",
3591 compoundStmt(hasParent(ifStmt()))));
3592 EXPECT_TRUE(notMatches(
3593 "void f() { if (true) for (;;) { int x = 42; } }",
3594 compoundStmt(hasParent(ifStmt()))));
3595}
3596
Manuel Klimek30ace372012-12-06 14:42:48 +00003597TEST(HasAncestor, MatchesAllAncestors) {
3598 EXPECT_TRUE(matches(
3599 "template <typename T> struct C { static void f() { 42; } };"
3600 "void t() { C<int>::f(); }",
3601 integerLiteral(
3602 equals(42),
3603 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3604 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3605}
3606
3607TEST(HasParent, MatchesAllParents) {
3608 EXPECT_TRUE(matches(
3609 "template <typename T> struct C { static void f() { 42; } };"
3610 "void t() { C<int>::f(); }",
3611 integerLiteral(
3612 equals(42),
3613 hasParent(compoundStmt(hasParent(functionDecl(
3614 hasParent(recordDecl(isTemplateInstantiation())))))))));
3615 EXPECT_TRUE(matches(
3616 "template <typename T> struct C { static void f() { 42; } };"
3617 "void t() { C<int>::f(); }",
3618 integerLiteral(
3619 equals(42),
3620 hasParent(compoundStmt(hasParent(functionDecl(
3621 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3622 EXPECT_TRUE(matches(
3623 "template <typename T> struct C { static void f() { 42; } };"
3624 "void t() { C<int>::f(); }",
3625 integerLiteral(equals(42),
3626 hasParent(compoundStmt(allOf(
3627 hasParent(functionDecl(
3628 hasParent(recordDecl(isTemplateInstantiation())))),
3629 hasParent(functionDecl(hasParent(recordDecl(
3630 unless(isTemplateInstantiation())))))))))));
Manuel Klimek374516c2013-03-14 16:33:21 +00003631 EXPECT_TRUE(
3632 notMatches("template <typename T> struct C { static void f() {} };"
3633 "void t() { C<int>::f(); }",
3634 compoundStmt(hasParent(recordDecl()))));
Manuel Klimek30ace372012-12-06 14:42:48 +00003635}
3636
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003637TEST(HasParent, NoDuplicateParents) {
3638 class HasDuplicateParents : public BoundNodesCallback {
3639 public:
3640 bool run(const BoundNodes *Nodes) override { return false; }
3641 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3642 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3643 std::set<const void *> Parents;
3644 for (const auto &Parent : Context->getParents(*Node)) {
3645 if (!Parents.insert(Parent.getMemoizationData()).second) {
3646 return true;
3647 }
3648 }
3649 return false;
3650 }
3651 };
3652 EXPECT_FALSE(matchAndVerifyResultTrue(
3653 "template <typename T> int Foo() { return 1 + 2; }\n"
3654 "int x = Foo<int>() + Foo<unsigned>();",
3655 stmt().bind("node"), new HasDuplicateParents()));
3656}
3657
Daniel Jasperce620072012-10-17 08:52:59 +00003658TEST(TypeMatching, MatchesTypes) {
3659 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3660}
3661
3662TEST(TypeMatching, MatchesArrayTypes) {
3663 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3664 EXPECT_TRUE(matches("int a[42];", arrayType()));
3665 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3666
3667 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3668 arrayType(hasElementType(builtinType()))));
3669
3670 EXPECT_TRUE(matches(
3671 "int const a[] = { 2, 3 };",
3672 qualType(arrayType(hasElementType(builtinType())))));
3673 EXPECT_TRUE(matches(
3674 "int const a[] = { 2, 3 };",
3675 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3676 EXPECT_TRUE(matches(
3677 "typedef const int T; T x[] = { 1, 2 };",
3678 qualType(isConstQualified(), arrayType())));
3679
3680 EXPECT_TRUE(notMatches(
3681 "int a[] = { 2, 3 };",
3682 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3683 EXPECT_TRUE(notMatches(
3684 "int a[] = { 2, 3 };",
3685 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3686 EXPECT_TRUE(notMatches(
3687 "int const a[] = { 2, 3 };",
3688 qualType(arrayType(hasElementType(builtinType())),
3689 unless(isConstQualified()))));
3690
3691 EXPECT_TRUE(matches("int a[2];",
3692 constantArrayType(hasElementType(builtinType()))));
3693 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3694}
3695
3696TEST(TypeMatching, MatchesComplexTypes) {
3697 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3698 EXPECT_TRUE(matches(
3699 "_Complex float f;",
3700 complexType(hasElementType(builtinType()))));
3701 EXPECT_TRUE(notMatches(
3702 "_Complex float f;",
3703 complexType(hasElementType(isInteger()))));
3704}
3705
3706TEST(TypeMatching, MatchesConstantArrayTypes) {
3707 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3708 EXPECT_TRUE(notMatches(
3709 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3710 constantArrayType(hasElementType(builtinType()))));
3711
3712 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3713 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3714 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3715}
3716
3717TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3718 EXPECT_TRUE(matches(
3719 "template <typename T, int Size> class array { T data[Size]; };",
3720 dependentSizedArrayType()));
3721 EXPECT_TRUE(notMatches(
3722 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3723 dependentSizedArrayType()));
3724}
3725
3726TEST(TypeMatching, MatchesIncompleteArrayType) {
3727 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3728 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3729
3730 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3731 incompleteArrayType()));
3732}
3733
3734TEST(TypeMatching, MatchesVariableArrayType) {
3735 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3736 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3737
3738 EXPECT_TRUE(matches(
3739 "void f(int b) { int a[b]; }",
3740 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3741 varDecl(hasName("b")))))))));
3742}
3743
3744TEST(TypeMatching, MatchesAtomicTypes) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003745 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3746 llvm::Triple::Win32) {
3747 // FIXME: Make this work for MSVC.
3748 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasperce620072012-10-17 08:52:59 +00003749
Stephen Hines651f13c2014-04-23 16:59:28 -07003750 EXPECT_TRUE(matches("_Atomic(int) i;",
3751 atomicType(hasValueType(isInteger()))));
3752 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3753 atomicType(hasValueType(isInteger()))));
3754 }
Daniel Jasperce620072012-10-17 08:52:59 +00003755}
3756
3757TEST(TypeMatching, MatchesAutoTypes) {
3758 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3759 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3760 autoType()));
3761
Richard Smith9b131752013-04-30 21:23:01 +00003762 // FIXME: Matching against the type-as-written can't work here, because the
3763 // type as written was not deduced.
3764 //EXPECT_TRUE(matches("auto a = 1;",
3765 // autoType(hasDeducedType(isInteger()))));
3766 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3767 // autoType(hasDeducedType(isInteger()))));
Daniel Jasperce620072012-10-17 08:52:59 +00003768}
3769
Daniel Jaspera267cf62012-10-29 10:14:44 +00003770TEST(TypeMatching, MatchesFunctionTypes) {
3771 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3772 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3773}
3774
Edwin Vane88be2fd2013-04-01 18:33:34 +00003775TEST(TypeMatching, MatchesParenType) {
3776 EXPECT_TRUE(
3777 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3778 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3779
3780 EXPECT_TRUE(matches(
3781 "int (*ptr_to_func)(int);",
3782 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3783 EXPECT_TRUE(notMatches(
3784 "int (*ptr_to_array)[4];",
3785 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3786}
3787
Daniel Jasperce620072012-10-17 08:52:59 +00003788TEST(TypeMatching, PointerTypes) {
Daniel Jasper1802daf2012-10-17 13:35:36 +00003789 // FIXME: Reactive when these tests can be more specific (not matching
3790 // implicit code on certain platforms), likely when we have hasDescendant for
3791 // Types/TypeLocs.
3792 //EXPECT_TRUE(matchAndVerifyResultTrue(
3793 // "int* a;",
3794 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3795 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3796 //EXPECT_TRUE(matchAndVerifyResultTrue(
3797 // "int* a;",
3798 // pointerTypeLoc().bind("loc"),
3799 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasperce620072012-10-17 08:52:59 +00003800 EXPECT_TRUE(matches(
3801 "int** a;",
David Blaikie5be093c2013-02-18 19:04:16 +00003802 loc(pointerType(pointee(qualType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00003803 EXPECT_TRUE(matches(
3804 "int** a;",
3805 loc(pointerType(pointee(pointerType())))));
3806 EXPECT_TRUE(matches(
3807 "int* b; int* * const a = &b;",
3808 loc(qualType(isConstQualified(), pointerType()))));
3809
3810 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper1802daf2012-10-17 13:35:36 +00003811 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3812 hasType(blockPointerType()))));
3813 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3814 hasType(memberPointerType()))));
3815 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3816 hasType(pointerType()))));
3817 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3818 hasType(referenceType()))));
Edwin Vanef4b48042013-03-07 15:44:40 +00003819 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3820 hasType(lValueReferenceType()))));
3821 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3822 hasType(rValueReferenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00003823
Daniel Jasper1802daf2012-10-17 13:35:36 +00003824 Fragment = "int *ptr;";
3825 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3826 hasType(blockPointerType()))));
3827 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3828 hasType(memberPointerType()))));
3829 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3830 hasType(pointerType()))));
3831 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3832 hasType(referenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00003833
Daniel Jasper1802daf2012-10-17 13:35:36 +00003834 Fragment = "int a; int &ref = a;";
3835 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3836 hasType(blockPointerType()))));
3837 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3838 hasType(memberPointerType()))));
3839 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3840 hasType(pointerType()))));
3841 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3842 hasType(referenceType()))));
Edwin Vanef4b48042013-03-07 15:44:40 +00003843 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3844 hasType(lValueReferenceType()))));
3845 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3846 hasType(rValueReferenceType()))));
3847
3848 Fragment = "int &&ref = 2;";
3849 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3850 hasType(blockPointerType()))));
3851 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3852 hasType(memberPointerType()))));
3853 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3854 hasType(pointerType()))));
3855 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3856 hasType(referenceType()))));
3857 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3858 hasType(lValueReferenceType()))));
3859 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3860 hasType(rValueReferenceType()))));
3861}
3862
3863TEST(TypeMatching, AutoRefTypes) {
3864 std::string Fragment = "auto a = 1;"
3865 "auto b = a;"
3866 "auto &c = a;"
3867 "auto &&d = c;"
3868 "auto &&e = 2;";
3869 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
3870 hasType(referenceType()))));
3871 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
3872 hasType(referenceType()))));
3873 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3874 hasType(referenceType()))));
3875 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3876 hasType(lValueReferenceType()))));
3877 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
3878 hasType(rValueReferenceType()))));
3879 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3880 hasType(referenceType()))));
3881 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3882 hasType(lValueReferenceType()))));
3883 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
3884 hasType(rValueReferenceType()))));
3885 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3886 hasType(referenceType()))));
3887 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
3888 hasType(lValueReferenceType()))));
3889 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3890 hasType(rValueReferenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00003891}
3892
3893TEST(TypeMatching, PointeeTypes) {
3894 EXPECT_TRUE(matches("int b; int &a = b;",
3895 referenceType(pointee(builtinType()))));
3896 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
3897
3898 EXPECT_TRUE(matches("int *a;",
David Blaikie5be093c2013-02-18 19:04:16 +00003899 loc(pointerType(pointee(builtinType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00003900
3901 EXPECT_TRUE(matches(
3902 "int const *A;",
3903 pointerType(pointee(isConstQualified(), builtinType()))));
3904 EXPECT_TRUE(notMatches(
3905 "int *A;",
3906 pointerType(pointee(isConstQualified(), builtinType()))));
3907}
3908
3909TEST(TypeMatching, MatchesPointersToConstTypes) {
3910 EXPECT_TRUE(matches("int b; int * const a = &b;",
3911 loc(pointerType())));
3912 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikie5be093c2013-02-18 19:04:16 +00003913 loc(pointerType())));
Daniel Jasperce620072012-10-17 08:52:59 +00003914 EXPECT_TRUE(matches(
3915 "int b; const int * a = &b;",
David Blaikie5be093c2013-02-18 19:04:16 +00003916 loc(pointerType(pointee(builtinType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00003917 EXPECT_TRUE(matches(
3918 "int b; const int * a = &b;",
3919 pointerType(pointee(builtinType()))));
3920}
3921
3922TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper1802daf2012-10-17 13:35:36 +00003923 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
3924 hasType(typedefType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00003925}
3926
Edwin Vane3abf7782013-02-25 14:49:29 +00003927TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vane742d9e72013-02-25 20:43:32 +00003928 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vane3abf7782013-02-25 14:49:29 +00003929 templateSpecializationType()));
3930}
3931
Edwin Vane742d9e72013-02-25 20:43:32 +00003932TEST(TypeMatching, MatchesRecordType) {
3933 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek0cc798f2013-02-27 11:56:58 +00003934 EXPECT_TRUE(matches("struct S{}; S s;",
3935 recordType(hasDeclaration(recordDecl(hasName("S"))))));
3936 EXPECT_TRUE(notMatches("int i;",
3937 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vane742d9e72013-02-25 20:43:32 +00003938}
3939
3940TEST(TypeMatching, MatchesElaboratedType) {
3941 EXPECT_TRUE(matches(
3942 "namespace N {"
3943 " namespace M {"
3944 " class D {};"
3945 " }"
3946 "}"
3947 "N::M::D d;", elaboratedType()));
3948 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
3949 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
3950}
3951
3952TEST(ElaboratedTypeNarrowing, hasQualifier) {
3953 EXPECT_TRUE(matches(
3954 "namespace N {"
3955 " namespace M {"
3956 " class D {};"
3957 " }"
3958 "}"
3959 "N::M::D d;",
3960 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
3961 EXPECT_TRUE(notMatches(
3962 "namespace M {"
3963 " class D {};"
3964 "}"
3965 "M::D d;",
3966 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vaneaec89ac2013-03-04 17:51:00 +00003967 EXPECT_TRUE(notMatches(
3968 "struct D {"
3969 "} d;",
3970 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vane742d9e72013-02-25 20:43:32 +00003971}
3972
3973TEST(ElaboratedTypeNarrowing, namesType) {
3974 EXPECT_TRUE(matches(
3975 "namespace N {"
3976 " namespace M {"
3977 " class D {};"
3978 " }"
3979 "}"
3980 "N::M::D d;",
3981 elaboratedType(elaboratedType(namesType(recordType(
3982 hasDeclaration(namedDecl(hasName("D")))))))));
3983 EXPECT_TRUE(notMatches(
3984 "namespace M {"
3985 " class D {};"
3986 "}"
3987 "M::D d;",
3988 elaboratedType(elaboratedType(namesType(typedefType())))));
3989}
3990
Daniel Jaspera7564432012-09-13 13:11:25 +00003991TEST(NNS, MatchesNestedNameSpecifiers) {
3992 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
3993 nestedNameSpecifier()));
3994 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
3995 nestedNameSpecifier()));
3996 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
3997 nestedNameSpecifier()));
3998
3999 EXPECT_TRUE(matches(
4000 "struct A { static void f() {} }; void g() { A::f(); }",
4001 nestedNameSpecifier()));
4002 EXPECT_TRUE(notMatches(
4003 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4004 nestedNameSpecifier()));
4005}
4006
Daniel Jasperb54b7642012-09-20 14:12:57 +00004007TEST(NullStatement, SimpleCases) {
4008 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4009 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4010}
4011
Daniel Jaspera7564432012-09-13 13:11:25 +00004012TEST(NNS, MatchesTypes) {
4013 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4014 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4015 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4016 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4017 Matcher));
4018 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4019}
4020
4021TEST(NNS, MatchesNamespaceDecls) {
4022 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4023 specifiesNamespace(hasName("ns")));
4024 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4025 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4026 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4027}
4028
4029TEST(NNS, BindsNestedNameSpecifiers) {
4030 EXPECT_TRUE(matchAndVerifyResultTrue(
4031 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4032 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4033 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4034}
4035
4036TEST(NNS, BindsNestedNameSpecifierLocs) {
4037 EXPECT_TRUE(matchAndVerifyResultTrue(
4038 "namespace ns { struct B {}; } ns::B b;",
4039 loc(nestedNameSpecifier()).bind("loc"),
4040 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4041}
4042
4043TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4044 EXPECT_TRUE(matches(
4045 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4046 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4047 EXPECT_TRUE(matches(
4048 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasperce620072012-10-17 08:52:59 +00004049 nestedNameSpecifierLoc(hasPrefix(
4050 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera7564432012-09-13 13:11:25 +00004051}
4052
Daniel Jasperd1ce3c12012-10-30 15:42:00 +00004053TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4054 std::string Fragment =
4055 "namespace a { struct A { struct B { struct C {}; }; }; };"
4056 "void f() { a::A::B::C c; }";
4057 EXPECT_TRUE(matches(
4058 Fragment,
4059 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4060 hasDescendant(nestedNameSpecifier(
4061 specifiesNamespace(hasName("a")))))));
4062 EXPECT_TRUE(notMatches(
4063 Fragment,
4064 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4065 has(nestedNameSpecifier(
4066 specifiesNamespace(hasName("a")))))));
4067 EXPECT_TRUE(matches(
4068 Fragment,
4069 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4070 has(nestedNameSpecifier(
4071 specifiesNamespace(hasName("a")))))));
4072
4073 // Not really useful because a NestedNameSpecifier can af at most one child,
4074 // but to complete the interface.
4075 EXPECT_TRUE(matchAndVerifyResultTrue(
4076 Fragment,
4077 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4078 forEach(nestedNameSpecifier().bind("x"))),
4079 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4080}
4081
4082TEST(NNS, NestedNameSpecifiersAsDescendants) {
4083 std::string Fragment =
4084 "namespace a { struct A { struct B { struct C {}; }; }; };"
4085 "void f() { a::A::B::C c; }";
4086 EXPECT_TRUE(matches(
4087 Fragment,
4088 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4089 asString("struct a::A")))))));
4090 EXPECT_TRUE(matchAndVerifyResultTrue(
4091 Fragment,
4092 functionDecl(hasName("f"),
4093 forEachDescendant(nestedNameSpecifier().bind("x"))),
4094 // Nested names: a, a::A and a::A::B.
4095 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4096}
4097
4098TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4099 std::string Fragment =
4100 "namespace a { struct A { struct B { struct C {}; }; }; };"
4101 "void f() { a::A::B::C c; }";
4102 EXPECT_TRUE(matches(
4103 Fragment,
4104 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4105 hasDescendant(loc(nestedNameSpecifier(
4106 specifiesNamespace(hasName("a"))))))));
4107 EXPECT_TRUE(notMatches(
4108 Fragment,
4109 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4110 has(loc(nestedNameSpecifier(
4111 specifiesNamespace(hasName("a"))))))));
4112 EXPECT_TRUE(matches(
4113 Fragment,
4114 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4115 has(loc(nestedNameSpecifier(
4116 specifiesNamespace(hasName("a"))))))));
4117
4118 EXPECT_TRUE(matchAndVerifyResultTrue(
4119 Fragment,
4120 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4121 forEach(nestedNameSpecifierLoc().bind("x"))),
4122 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4123}
4124
4125TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4126 std::string Fragment =
4127 "namespace a { struct A { struct B { struct C {}; }; }; };"
4128 "void f() { a::A::B::C c; }";
4129 EXPECT_TRUE(matches(
4130 Fragment,
4131 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4132 asString("struct a::A"))))))));
4133 EXPECT_TRUE(matchAndVerifyResultTrue(
4134 Fragment,
4135 functionDecl(hasName("f"),
4136 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4137 // Nested names: a, a::A and a::A::B.
4138 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4139}
4140
Manuel Klimek60969f52013-02-01 13:41:35 +00004141template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004142public:
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004143 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4144 StringRef InnerId)
4145 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jasper452abbc2012-10-29 10:48:25 +00004146 }
4147
Manuel Klimek60969f52013-02-01 13:41:35 +00004148 virtual bool run(const BoundNodes *Nodes) { return false; }
4149
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004150 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4151 const T *Node = Nodes->getNodeAs<T>(Id);
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004152 return selectFirst<const T>(InnerId,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004153 match(InnerMatcher, *Node, *Context)) !=nullptr;
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004154 }
4155private:
4156 std::string Id;
4157 internal::Matcher<T> InnerMatcher;
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004158 std::string InnerId;
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004159};
4160
4161TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek60969f52013-02-01 13:41:35 +00004162 EXPECT_TRUE(matchAndVerifyResultTrue(
4163 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4164 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004165 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4166 "Y")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004167 EXPECT_TRUE(matchAndVerifyResultFalse(
4168 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4169 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004170 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4171 "Z")));
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004172}
4173
4174TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek60969f52013-02-01 13:41:35 +00004175 EXPECT_TRUE(matchAndVerifyResultTrue(
4176 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004177 new VerifyMatchOnNode<clang::Stmt>(
4178 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004179 EXPECT_TRUE(matchAndVerifyResultFalse(
4180 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004181 new VerifyMatchOnNode<clang::Stmt>(
4182 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004183}
4184
4185TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4186 EXPECT_TRUE(matchAndVerifyResultTrue(
4187 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4188 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004189 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004190 EXPECT_TRUE(matchAndVerifyResultFalse(
4191 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4192 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004193 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004194}
4195
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004196template <typename T>
4197class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4198public:
4199 virtual bool run(const BoundNodes *Nodes) { return false; }
4200
4201 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4202 const T *Node = Nodes->getNodeAs<T>("");
4203 return verify(*Nodes, *Context, Node);
4204 }
4205
4206 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004207 // Use the original typed pointer to verify we can pass pointers to subtypes
4208 // to equalsNode.
4209 const T *TypedNode = cast<T>(Node);
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004210 return selectFirst<const T>(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004211 "", match(stmt(hasParent(
4212 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004213 *Node, Context)) != nullptr;
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004214 }
4215 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004216 // Use the original typed pointer to verify we can pass pointers to subtypes
4217 // to equalsNode.
4218 const T *TypedNode = cast<T>(Node);
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004219 return selectFirst<const T>(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004220 "", match(decl(hasParent(
4221 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004222 *Node, Context)) != nullptr;
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004223 }
4224};
4225
4226TEST(IsEqualTo, MatchesNodesByIdentity) {
4227 EXPECT_TRUE(matchAndVerifyResultTrue(
4228 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004229 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4230 EXPECT_TRUE(matchAndVerifyResultTrue(
4231 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4232 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004233}
4234
Manuel Klimeke5793282012-11-02 01:31:03 +00004235class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4236public:
4237 VerifyStartOfTranslationUnit() : Called(false) {}
4238 virtual void run(const MatchFinder::MatchResult &Result) {
4239 EXPECT_TRUE(Called);
4240 }
4241 virtual void onStartOfTranslationUnit() {
4242 Called = true;
4243 }
4244 bool Called;
4245};
4246
4247TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4248 MatchFinder Finder;
4249 VerifyStartOfTranslationUnit VerifyCallback;
4250 Finder.addMatcher(decl(), &VerifyCallback);
Stephen Hines651f13c2014-04-23 16:59:28 -07004251 std::unique_ptr<FrontendActionFactory> Factory(
4252 newFrontendActionFactory(&Finder));
Manuel Klimeke5793282012-11-02 01:31:03 +00004253 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4254 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004255
4256 VerifyCallback.Called = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004257 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004258 ASSERT_TRUE(AST.get());
4259 Finder.matchAST(AST->getASTContext());
4260 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimeke5793282012-11-02 01:31:03 +00004261}
4262
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004263class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4264public:
4265 VerifyEndOfTranslationUnit() : Called(false) {}
4266 virtual void run(const MatchFinder::MatchResult &Result) {
4267 EXPECT_FALSE(Called);
4268 }
4269 virtual void onEndOfTranslationUnit() {
4270 Called = true;
4271 }
4272 bool Called;
4273};
4274
4275TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4276 MatchFinder Finder;
4277 VerifyEndOfTranslationUnit VerifyCallback;
4278 Finder.addMatcher(decl(), &VerifyCallback);
Stephen Hines651f13c2014-04-23 16:59:28 -07004279 std::unique_ptr<FrontendActionFactory> Factory(
4280 newFrontendActionFactory(&Finder));
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004281 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4282 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004283
4284 VerifyCallback.Called = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004285 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004286 ASSERT_TRUE(AST.get());
4287 Finder.matchAST(AST->getASTContext());
4288 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004289}
4290
Manuel Klimekcf52ca62013-06-20 14:06:32 +00004291TEST(EqualsBoundNodeMatcher, QualType) {
4292 EXPECT_TRUE(matches(
4293 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4294 hasInitializer(ignoringParenImpCasts(
4295 hasType(qualType(equalsBoundNode("type"))))))));
4296 EXPECT_TRUE(notMatches("int i = 1.f;",
4297 varDecl(hasType(qualType().bind("type")),
4298 hasInitializer(ignoringParenImpCasts(hasType(
4299 qualType(equalsBoundNode("type"))))))));
4300}
4301
4302TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4303 EXPECT_TRUE(notMatches(
4304 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4305 hasInitializer(ignoringParenImpCasts(
4306 hasType(qualType(equalsBoundNode("type"))))))));
4307}
4308
4309TEST(EqualsBoundNodeMatcher, Stmt) {
4310 EXPECT_TRUE(
4311 matches("void f() { if(true) {} }",
4312 stmt(allOf(ifStmt().bind("if"),
4313 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4314
4315 EXPECT_TRUE(notMatches(
4316 "void f() { if(true) { if (true) {} } }",
4317 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4318}
4319
4320TEST(EqualsBoundNodeMatcher, Decl) {
4321 EXPECT_TRUE(matches(
4322 "class X { class Y {}; };",
4323 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4324 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4325
4326 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4327 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4328 has(decl(equalsBoundNode("record")))))));
4329}
4330
4331TEST(EqualsBoundNodeMatcher, Type) {
4332 EXPECT_TRUE(matches(
4333 "class X { int a; int b; };",
4334 recordDecl(
4335 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4336 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4337
4338 EXPECT_TRUE(notMatches(
4339 "class X { int a; double b; };",
4340 recordDecl(
4341 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4342 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4343}
4344
4345TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekcf52ca62013-06-20 14:06:32 +00004346 EXPECT_TRUE(matchAndVerifyResultTrue(
4347 "int f() {"
4348 " if (1) {"
4349 " int i = 9;"
4350 " }"
4351 " int j = 10;"
4352 " {"
4353 " float k = 9.0;"
4354 " }"
4355 " return 0;"
4356 "}",
4357 // Look for variable declarations within functions whose type is the same
4358 // as the function return type.
4359 functionDecl(returns(qualType().bind("type")),
4360 forEachDescendant(varDecl(hasType(
4361 qualType(equalsBoundNode("type")))).bind("decl"))),
4362 // Only i and j should match, not k.
4363 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4364}
4365
4366TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4367 EXPECT_TRUE(matchAndVerifyResultTrue(
4368 "void f() {"
4369 " int x;"
4370 " double d;"
4371 " x = d + x - d + x;"
4372 "}",
4373 functionDecl(
4374 hasName("f"), forEachDescendant(varDecl().bind("d")),
4375 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4376 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4377}
4378
Stephen Hines651f13c2014-04-23 16:59:28 -07004379TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4380 EXPECT_TRUE(matchAndVerifyResultTrue(
4381 "struct StringRef { int size() const; const char* data() const; };"
4382 "void f(StringRef v) {"
4383 " v.data();"
4384 "}",
4385 memberCallExpr(
4386 callee(methodDecl(hasName("data"))),
4387 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4388 .bind("var")))),
4389 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4390 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4391 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4392 .bind("data"),
4393 new VerifyIdIsBoundTo<Expr>("data", 1)));
4394
4395 EXPECT_FALSE(matches(
4396 "struct StringRef { int size() const; const char* data() const; };"
4397 "void f(StringRef v) {"
4398 " v.data();"
4399 " v.size();"
4400 "}",
4401 memberCallExpr(
4402 callee(methodDecl(hasName("data"))),
4403 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4404 .bind("var")))),
4405 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4406 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4407 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4408 .bind("data")));
4409}
4410
Manuel Klimek4da21662012-07-06 05:48:52 +00004411} // end namespace ast_matchers
4412} // end namespace clang