blob: c88a197643a7d36ef5e8be7fe76ecb0abb3b28f8 [file] [log] [blame]
Manuel Klimek4da21662012-07-06 05:48:52 +00001//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher unit tests ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ASTMatchersTest.h"
Benjamin Kramer8b9ed712012-12-01 17:22:05 +000011#include "clang/AST/PrettyPrinter.h"
Manuel Klimek4da21662012-07-06 05:48:52 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Chandler Carruth1050e8b2012-12-04 09:45:34 +000013#include "clang/ASTMatchers/ASTMatchers.h"
Manuel Klimek4da21662012-07-06 05:48:52 +000014#include "clang/Tooling/Tooling.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070015#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
Manuel Klimek4da21662012-07-06 05:48:52 +000017#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
Benjamin Kramer78a0ce42012-07-10 17:30:44 +000022#if GTEST_HAS_DEATH_TEST
Manuel Klimek4da21662012-07-06 05:48:52 +000023TEST(HasNameDeathTest, DiesOnEmptyName) {
24 ASSERT_DEBUG_DEATH({
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000025 DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
Manuel Klimek4da21662012-07-06 05:48:52 +000026 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27 }, "");
28}
29
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000030TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31 ASSERT_DEBUG_DEATH({
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000032 DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000033 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34 }, "");
35}
36
Manuel Klimek4da21662012-07-06 05:48:52 +000037TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38 ASSERT_DEBUG_DEATH({
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000039 DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
Manuel Klimek4da21662012-07-06 05:48:52 +000040 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41 }, "");
42}
Benjamin Kramer78a0ce42012-07-10 17:30:44 +000043#endif
Manuel Klimek4da21662012-07-06 05:48:52 +000044
Peter Collingbourned2bd5892013-11-07 22:30:32 +000045TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46 MatchFinder Finder;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070047 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50 nullptr));
Peter Collingbourned2bd5892013-11-07 22:30:32 +000051
52 // Do not accept non-toplevel matchers.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070053 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54 EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
Peter Collingbourned2bd5892013-11-07 22:30:32 +000056}
57
Manuel Klimek715c9562012-07-25 10:02:02 +000058TEST(Decl, MatchesDeclarations) {
59 EXPECT_TRUE(notMatches("", decl(usingDecl())));
60 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
61 decl(usingDecl())));
62}
63
Manuel Klimek4da21662012-07-06 05:48:52 +000064TEST(NameableDeclaration, MatchesVariousDecls) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000065 DeclarationMatcher NamedX = namedDecl(hasName("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +000066 EXPECT_TRUE(matches("typedef int X;", NamedX));
67 EXPECT_TRUE(matches("int X;", NamedX));
68 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
69 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
70 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
71 EXPECT_TRUE(matches("namespace X { }", NamedX));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000072 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
Manuel Klimek4da21662012-07-06 05:48:52 +000073
74 EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000077TEST(NameableDeclaration, REMatchesVariousDecls) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000078 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000079 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
80 EXPECT_TRUE(matches("int Xb;", NamedX));
81 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
82 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
83 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
84 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
85 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
86
87 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
88
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000089 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000090 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
91 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
92
Daniel Jasper2dc75ed2012-08-24 05:12:34 +000093 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000094 EXPECT_TRUE(matches("int abc;", Abc));
95 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
96 EXPECT_TRUE(notMatches("int cab;", Abc));
97 EXPECT_TRUE(matches("int cabc;", Abc));
Manuel Klimekec33b6f2012-12-10 07:08:53 +000098
99 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
100 EXPECT_TRUE(matches("int k;", StartsWithK));
101 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
102 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
103 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
104 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000105}
106
Manuel Klimek4da21662012-07-06 05:48:52 +0000107TEST(DeclarationMatcher, MatchClass) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000108 DeclarationMatcher ClassMatcher(recordDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -0700109 llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110 if (Triple.getOS() != llvm::Triple::Win32 ||
111 Triple.getEnvironment() != llvm::Triple::MSVC)
112 EXPECT_FALSE(matches("", ClassMatcher));
113 else
114 // Matches class type_info.
115 EXPECT_TRUE(matches("", ClassMatcher));
Manuel Klimek4da21662012-07-06 05:48:52 +0000116
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000117 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000118 EXPECT_TRUE(matches("class X;", ClassX));
119 EXPECT_TRUE(matches("class X {};", ClassX));
120 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
121 EXPECT_TRUE(notMatches("", ClassX));
122}
123
124TEST(DeclarationMatcher, ClassIsDerived) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000125 DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000126
127 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
Daniel Jasper76dafa72012-09-07 12:48:17 +0000128 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
Manuel Klimek4da21662012-07-06 05:48:52 +0000130 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131 EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
Daniel Jasper63d88722012-09-12 21:14:15 +0000133 DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
Daniel Jasper76dafa72012-09-07 12:48:17 +0000134
135 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
136 EXPECT_TRUE(matches("class X {};", IsAX));
137 EXPECT_TRUE(matches("class X;", IsAX));
138 EXPECT_TRUE(notMatches("class Y;", IsAX));
139 EXPECT_TRUE(notMatches("", IsAX));
140
Manuel Klimek4da21662012-07-06 05:48:52 +0000141 DeclarationMatcher ZIsDerivedFromX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000142 recordDecl(hasName("Z"), isDerivedFrom("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000143 EXPECT_TRUE(
144 matches("class X {}; class Y : public X {}; class Z : public Y {};",
145 ZIsDerivedFromX));
146 EXPECT_TRUE(
147 matches("class X {};"
148 "template<class T> class Y : public X {};"
149 "class Z : public Y<int> {};", ZIsDerivedFromX));
150 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
151 ZIsDerivedFromX));
152 EXPECT_TRUE(
153 matches("template<class T> class X {}; "
154 "template<class T> class Z : public X<T> {};",
155 ZIsDerivedFromX));
156 EXPECT_TRUE(
157 matches("template<class T, class U=T> class X {}; "
158 "template<class T> class Z : public X<T> {};",
159 ZIsDerivedFromX));
160 EXPECT_TRUE(
161 notMatches("template<class X> class A { class Z : public X {}; };",
162 ZIsDerivedFromX));
163 EXPECT_TRUE(
164 matches("template<class X> class A { public: class Z : public X {}; }; "
165 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
166 EXPECT_TRUE(
167 matches("template <class T> class X {}; "
168 "template<class Y> class A { class Z : public X<Y> {}; };",
169 ZIsDerivedFromX));
170 EXPECT_TRUE(
171 notMatches("template<template<class T> class X> class A { "
172 " class Z : public X<int> {}; };", ZIsDerivedFromX));
173 EXPECT_TRUE(
174 matches("template<template<class T> class X> class A { "
175 " public: class Z : public X<int> {}; }; "
176 "template<class T> class X {}; void y() { A<X>::Z z; }",
177 ZIsDerivedFromX));
178 EXPECT_TRUE(
179 notMatches("template<class X> class A { class Z : public X::D {}; };",
180 ZIsDerivedFromX));
181 EXPECT_TRUE(
182 matches("template<class X> class A { public: "
183 " class Z : public X::D {}; }; "
184 "class Y { public: class X {}; typedef X D; }; "
185 "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
186 EXPECT_TRUE(
187 matches("class X {}; typedef X Y; class Z : public Y {};",
188 ZIsDerivedFromX));
189 EXPECT_TRUE(
190 matches("template<class T> class Y { typedef typename T::U X; "
191 " class Z : public X {}; };", ZIsDerivedFromX));
192 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
193 ZIsDerivedFromX));
194 EXPECT_TRUE(
195 notMatches("template<class T> class X {}; "
196 "template<class T> class A { class Z : public X<T>::D {}; };",
197 ZIsDerivedFromX));
198 EXPECT_TRUE(
199 matches("template<class T> class X { public: typedef X<T> D; }; "
200 "template<class T> class A { public: "
201 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
202 ZIsDerivedFromX));
203 EXPECT_TRUE(
204 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
205 ZIsDerivedFromX));
206 EXPECT_TRUE(
207 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
208 ZIsDerivedFromX));
209 EXPECT_TRUE(
210 matches("class X {}; class Y : public X {}; "
211 "typedef Y V; typedef V W; class Z : public W {};",
212 ZIsDerivedFromX));
213 EXPECT_TRUE(
214 matches("template<class T, class U> class X {}; "
215 "template<class T> class A { class Z : public X<T, int> {}; };",
216 ZIsDerivedFromX));
217 EXPECT_TRUE(
218 notMatches("template<class X> class D { typedef X A; typedef A B; "
219 " typedef B C; class Z : public C {}; };",
220 ZIsDerivedFromX));
221 EXPECT_TRUE(
222 matches("class X {}; typedef X A; typedef A B; "
223 "class Z : public B {};", ZIsDerivedFromX));
224 EXPECT_TRUE(
225 matches("class X {}; typedef X A; typedef A B; typedef B C; "
226 "class Z : public C {};", ZIsDerivedFromX));
227 EXPECT_TRUE(
228 matches("class U {}; typedef U X; typedef X V; "
229 "class Z : public V {};", ZIsDerivedFromX));
230 EXPECT_TRUE(
231 matches("class Base {}; typedef Base X; "
232 "class Z : public Base {};", ZIsDerivedFromX));
233 EXPECT_TRUE(
234 matches("class Base {}; typedef Base Base2; typedef Base2 X; "
235 "class Z : public Base {};", ZIsDerivedFromX));
236 EXPECT_TRUE(
237 notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
238 "class Z : public Base {};", ZIsDerivedFromX));
239 EXPECT_TRUE(
240 matches("class A {}; typedef A X; typedef A Y; "
241 "class Z : public Y {};", ZIsDerivedFromX));
242 EXPECT_TRUE(
243 notMatches("template <typename T> class Z;"
244 "template <> class Z<void> {};"
245 "template <typename T> class Z : public Z<void> {};",
246 IsDerivedFromX));
247 EXPECT_TRUE(
248 matches("template <typename T> class X;"
249 "template <> class X<void> {};"
250 "template <typename T> class X : public X<void> {};",
251 IsDerivedFromX));
252 EXPECT_TRUE(matches(
253 "class X {};"
254 "template <typename T> class Z;"
255 "template <> class Z<void> {};"
256 "template <typename T> class Z : public Z<void>, public X {};",
257 ZIsDerivedFromX));
Manuel Klimek987c2f52012-12-04 13:40:29 +0000258 EXPECT_TRUE(
259 notMatches("template<int> struct X;"
260 "template<int i> struct X : public X<i-1> {};",
261 recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
262 EXPECT_TRUE(matches(
263 "struct A {};"
264 "template<int> struct X;"
265 "template<int i> struct X : public X<i-1> {};"
266 "template<> struct X<0> : public A {};"
267 "struct B : public X<42> {};",
268 recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000269
270 // FIXME: Once we have better matchers for template type matching,
271 // get rid of the Variable(...) matching and match the right template
272 // declarations directly.
273 const char *RecursiveTemplateOneParameter =
274 "class Base1 {}; class Base2 {};"
275 "template <typename T> class Z;"
276 "template <> class Z<void> : public Base1 {};"
277 "template <> class Z<int> : public Base2 {};"
278 "template <> class Z<float> : public Z<void> {};"
279 "template <> class Z<double> : public Z<int> {};"
280 "template <typename T> class Z : public Z<float>, public Z<double> {};"
281 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
282 EXPECT_TRUE(matches(
283 RecursiveTemplateOneParameter,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000284 varDecl(hasName("z_float"),
285 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000286 EXPECT_TRUE(notMatches(
287 RecursiveTemplateOneParameter,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000288 varDecl(hasName("z_float"),
289 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000290 EXPECT_TRUE(matches(
291 RecursiveTemplateOneParameter,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000292 varDecl(hasName("z_char"),
293 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
294 isDerivedFrom("Base2")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000295
296 const char *RecursiveTemplateTwoParameters =
297 "class Base1 {}; class Base2 {};"
298 "template <typename T1, typename T2> class Z;"
299 "template <typename T> class Z<void, T> : public Base1 {};"
300 "template <typename T> class Z<int, T> : public Base2 {};"
301 "template <typename T> class Z<float, T> : public Z<void, T> {};"
302 "template <typename T> class Z<double, T> : public Z<int, T> {};"
303 "template <typename T1, typename T2> class Z : "
304 " public Z<float, T2>, public Z<double, T2> {};"
305 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
306 " Z<char, void> z_char; }";
307 EXPECT_TRUE(matches(
308 RecursiveTemplateTwoParameters,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000309 varDecl(hasName("z_float"),
310 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000311 EXPECT_TRUE(notMatches(
312 RecursiveTemplateTwoParameters,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000313 varDecl(hasName("z_float"),
314 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000315 EXPECT_TRUE(matches(
316 RecursiveTemplateTwoParameters,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000317 varDecl(hasName("z_char"),
318 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
319 isDerivedFrom("Base2")))))));
Daniel Jasper20b802d2012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000322 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper20b802d2012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000325 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper20b802d2012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000329 recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
Manuel Klimekb56da8c2013-08-02 21:24:09 +0000330
331 EXPECT_TRUE(matches(
332 "template<typename T> class X {};"
333 "template<typename T> using Z = X<T>;"
334 "template <typename T> class Y : Z<T> {};",
335 recordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000336}
337
Edwin Vane6a19a972013-03-06 17:02:57 +0000338TEST(DeclarationMatcher, hasMethod) {
339 EXPECT_TRUE(matches("class A { void func(); };",
340 recordDecl(hasMethod(hasName("func")))));
341 EXPECT_TRUE(notMatches("class A { void func(); };",
342 recordDecl(hasMethod(isPublic()))));
343}
344
Daniel Jasper08f0c532012-09-18 14:17:42 +0000345TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
346 EXPECT_TRUE(matches(
347 "template <typename T> struct A {"
348 " template <typename T2> struct F {};"
349 "};"
350 "template <typename T> struct B : A<T>::template F<T> {};"
351 "B<int> b;",
352 recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
353}
354
Edwin Vane742d9e72013-02-25 20:43:32 +0000355TEST(DeclarationMatcher, hasDeclContext) {
356 EXPECT_TRUE(matches(
357 "namespace N {"
358 " namespace M {"
359 " class D {};"
360 " }"
361 "}",
Daniel Jasperabe92232013-04-08 16:44:05 +0000362 recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
Edwin Vane742d9e72013-02-25 20:43:32 +0000363 EXPECT_TRUE(notMatches(
364 "namespace N {"
365 " namespace M {"
366 " class D {};"
367 " }"
368 "}",
Daniel Jasperabe92232013-04-08 16:44:05 +0000369 recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
370
371 EXPECT_TRUE(matches("namespace {"
372 " namespace M {"
373 " class D {};"
374 " }"
375 "}",
376 recordDecl(hasDeclContext(namespaceDecl(
377 hasName("M"), hasDeclContext(namespaceDecl()))))));
Stephen Hines176edba2014-12-01 14:53:08 -0800378
379 EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
380}
381
382TEST(DeclarationMatcher, LinkageSpecification) {
383 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
384 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
Edwin Vane742d9e72013-02-25 20:43:32 +0000385}
386
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000387TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000388 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000389 EXPECT_TRUE(notMatches("class X;", ClassX));
390 EXPECT_TRUE(notMatches("class X {};", ClassX));
391}
392
393TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000394 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000395 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
396 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
397}
398
399TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
400 EXPECT_TRUE(notMatches("template<typename T> class X { };"
401 "template<> class X<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
406TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
407 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
408 "template<typename T> class X<T, int> { int a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000409 classTemplateDecl(hasName("X"),
410 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +0000411}
412
Daniel Jasper6a124492012-07-12 08:50:38 +0000413TEST(AllOf, AllOverloadsWork) {
414 const char Program[] =
Edwin Vane7f43fcf2013-02-12 13:55:40 +0000415 "struct T { };"
416 "int f(int, T*, int, int);"
417 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper6a124492012-07-12 08:50:38 +0000418 EXPECT_TRUE(matches(Program,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000419 callExpr(allOf(callee(functionDecl(hasName("f"))),
420 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper6a124492012-07-12 08:50:38 +0000421 EXPECT_TRUE(matches(Program,
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000422 callExpr(allOf(callee(functionDecl(hasName("f"))),
423 hasArgument(0, declRefExpr(to(varDecl()))),
424 hasArgument(1, hasType(pointsTo(
425 recordDecl(hasName("T")))))))));
Edwin Vane7f43fcf2013-02-12 13:55:40 +0000426 EXPECT_TRUE(matches(Program,
427 callExpr(allOf(callee(functionDecl(hasName("f"))),
428 hasArgument(0, declRefExpr(to(varDecl()))),
429 hasArgument(1, hasType(pointsTo(
430 recordDecl(hasName("T"))))),
431 hasArgument(2, integerLiteral(equals(3)))))));
432 EXPECT_TRUE(matches(Program,
433 callExpr(allOf(callee(functionDecl(hasName("f"))),
434 hasArgument(0, declRefExpr(to(varDecl()))),
435 hasArgument(1, hasType(pointsTo(
436 recordDecl(hasName("T"))))),
437 hasArgument(2, integerLiteral(equals(3))),
438 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper6a124492012-07-12 08:50:38 +0000439}
440
Manuel Klimek4da21662012-07-06 05:48:52 +0000441TEST(DeclarationMatcher, MatchAnyOf) {
442 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000443 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000444 EXPECT_TRUE(
445 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
446 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
447 EXPECT_TRUE(
448 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
449 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
450
Daniel Jasperff2fcb82012-07-15 19:57:12 +0000451 DeclarationMatcher XOrYOrZOrU =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000452 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasperff2fcb82012-07-15 19:57:12 +0000453 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
454 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
455
Manuel Klimek4da21662012-07-06 05:48:52 +0000456 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000457 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
458 hasName("V")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000459 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
460 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
461 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
462 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
463 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
464 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Stephen Hines176edba2014-12-01 14:53:08 -0800465
466 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
467 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
468 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
469 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Manuel Klimek4da21662012-07-06 05:48:52 +0000470}
471
472TEST(DeclarationMatcher, MatchHas) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000473 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000474 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
475 EXPECT_TRUE(matches("class X {};", HasClassX));
476
477 DeclarationMatcher YHasClassX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000478 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000479 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
480 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
481 EXPECT_TRUE(
482 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
483}
484
485TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
486 DeclarationMatcher Recursive =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000487 recordDecl(
488 has(recordDecl(
489 has(recordDecl(hasName("X"))),
490 has(recordDecl(hasName("Y"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000491 hasName("Z"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000492 has(recordDecl(
493 has(recordDecl(hasName("A"))),
494 has(recordDecl(hasName("B"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000495 hasName("C"))),
496 hasName("F"));
497
498 EXPECT_TRUE(matches(
499 "class F {"
500 " class Z {"
501 " class X {};"
502 " class Y {};"
503 " };"
504 " class C {"
505 " class A {};"
506 " class B {};"
507 " };"
508 "};", Recursive));
509
510 EXPECT_TRUE(matches(
511 "class F {"
512 " class Z {"
513 " class A {};"
514 " class X {};"
515 " class Y {};"
516 " };"
517 " class C {"
518 " class X {};"
519 " class A {};"
520 " class B {};"
521 " };"
522 "};", Recursive));
523
524 EXPECT_TRUE(matches(
525 "class O1 {"
526 " class O2 {"
527 " class F {"
528 " class Z {"
529 " class A {};"
530 " class X {};"
531 " class Y {};"
532 " };"
533 " class C {"
534 " class X {};"
535 " class A {};"
536 " class B {};"
537 " };"
538 " };"
539 " };"
540 "};", Recursive));
541}
542
543TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
544 DeclarationMatcher Recursive =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000545 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000546 anyOf(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000547 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000548 anyOf(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000549 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000550 hasName("X"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000551 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000552 hasName("Y"))),
553 hasName("Z")))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000554 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000555 anyOf(
556 hasName("C"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000557 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000558 hasName("A"))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000559 has(recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000560 hasName("B")))))),
561 hasName("F")));
562
563 EXPECT_TRUE(matches("class F {};", Recursive));
564 EXPECT_TRUE(matches("class Z {};", Recursive));
565 EXPECT_TRUE(matches("class C {};", Recursive));
566 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
567 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
568 EXPECT_TRUE(
569 matches("class O1 { class O2 {"
570 " class M { class N { class B {}; }; }; "
571 "}; };", Recursive));
572}
573
574TEST(DeclarationMatcher, MatchNot) {
575 DeclarationMatcher NotClassX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000576 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000577 isDerivedFrom("Y"),
Manuel Klimek4da21662012-07-06 05:48:52 +0000578 unless(hasName("X")));
579 EXPECT_TRUE(notMatches("", NotClassX));
580 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
581 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
582 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
583 EXPECT_TRUE(
584 notMatches("class Y {}; class Z {}; class X : public Y {};",
585 NotClassX));
586
587 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000588 recordDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +0000589 hasName("X"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000590 has(recordDecl(hasName("Z"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000591 unless(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000592 has(recordDecl(hasName("Y")))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000593 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
594 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
595 ClassXHasNotClassY));
Stephen Hines176edba2014-12-01 14:53:08 -0800596
597 DeclarationMatcher NamedNotRecord =
598 namedDecl(hasName("Foo"), unless(recordDecl()));
599 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
600 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek4da21662012-07-06 05:48:52 +0000601}
602
603TEST(DeclarationMatcher, HasDescendant) {
604 DeclarationMatcher ZDescendantClassX =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000605 recordDecl(
606 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000607 hasName("Z"));
608 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
609 EXPECT_TRUE(
610 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
611 EXPECT_TRUE(
612 matches("class Z { class A { class Y { class X {}; }; }; };",
613 ZDescendantClassX));
614 EXPECT_TRUE(
615 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
616 ZDescendantClassX));
617 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
618
619 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000620 recordDecl(
621 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000622 hasName("X"))),
623 hasName("Z"));
624 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
625 ZDescendantClassXHasClassY));
626 EXPECT_TRUE(
627 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
628 ZDescendantClassXHasClassY));
629 EXPECT_TRUE(notMatches(
630 "class Z {"
631 " class A {"
632 " class B {"
633 " class X {"
634 " class C {"
635 " class Y {};"
636 " };"
637 " };"
638 " }; "
639 " };"
640 "};", ZDescendantClassXHasClassY));
641
642 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000643 recordDecl(
644 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
645 hasName("X"))),
Manuel Klimek4da21662012-07-06 05:48:52 +0000646 hasName("Z"));
647 EXPECT_TRUE(
648 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
649 ZDescendantClassXDescendantClassY));
650 EXPECT_TRUE(matches(
651 "class Z {"
652 " class A {"
653 " class X {"
654 " class B {"
655 " class Y {};"
656 " };"
657 " class Y {};"
658 " };"
659 " };"
660 "};", ZDescendantClassXDescendantClassY));
661}
662
Stephen Hines176edba2014-12-01 14:53:08 -0800663TEST(DeclarationMatcher, HasDescendantMemoization) {
664 DeclarationMatcher CannotMemoize =
665 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
666 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
667}
668
669TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
670 auto Name = hasName("i");
671 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
672 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
673 // Matching VD first should not make a cache hit for RD.
674 EXPECT_TRUE(notMatches("void f() { int i; }",
675 decl(hasDescendant(VD), hasDescendant(RD))));
676 EXPECT_TRUE(notMatches("void f() { int i; }",
677 decl(hasDescendant(RD), hasDescendant(VD))));
678 // Not matching RD first should not make a cache hit for VD either.
679 EXPECT_TRUE(matches("void f() { int i; }",
680 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
681}
682
683TEST(DeclarationMatcher, HasAttr) {
684 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
685 decl(hasAttr(clang::attr::WarnUnused))));
686 EXPECT_FALSE(matches("struct X {};",
687 decl(hasAttr(clang::attr::WarnUnused))));
688}
689
690TEST(DeclarationMatcher, MatchCudaDecl) {
691 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
692 "void g() { f<<<1, 2>>>(); }",
693 CUDAKernelCallExpr()));
694 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
695 hasAttr(clang::attr::CUDADevice)));
696 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
697 CUDAKernelCallExpr()));
698 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
699 hasAttr(clang::attr::CUDAGlobal)));
700}
701
Daniel Jaspera267cf62012-10-29 10:14:44 +0000702// Implements a run method that returns whether BoundNodes contains a
703// Decl bound to Id that can be dynamically cast to T.
704// Optionally checks that the check succeeded a specific number of times.
705template <typename T>
706class VerifyIdIsBoundTo : public BoundNodesCallback {
707public:
708 // Create an object that checks that a node of type \c T was bound to \c Id.
709 // Does not check for a certain number of matches.
710 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
711 : Id(Id), ExpectedCount(-1), Count(0) {}
712
713 // Create an object that checks that a node of type \c T was bound to \c Id.
714 // Checks that there were exactly \c ExpectedCount matches.
715 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
716 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
717
718 // Create an object that checks that a node of type \c T was bound to \c Id.
719 // Checks that there was exactly one match with the name \c ExpectedName.
720 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimek374516c2013-03-14 16:33:21 +0000721 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
722 int ExpectedCount = 1)
723 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
724 ExpectedName(ExpectedName) {}
Daniel Jaspera267cf62012-10-29 10:14:44 +0000725
Stephen Hines651f13c2014-04-23 16:59:28 -0700726 void onEndOfTranslationUnit() override {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000727 if (ExpectedCount != -1)
728 EXPECT_EQ(ExpectedCount, Count);
729 if (!ExpectedName.empty())
730 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourned2bd5892013-11-07 22:30:32 +0000731 Count = 0;
732 Name.clear();
733 }
734
735 ~VerifyIdIsBoundTo() {
736 EXPECT_EQ(0, Count);
737 EXPECT_EQ("", Name);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000738 }
739
Stephen Hines176edba2014-12-01 14:53:08 -0800740 virtual bool run(const BoundNodes *Nodes) override {
Peter Collingbourne3f0e0402013-11-06 00:27:07 +0000741 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jaspera267cf62012-10-29 10:14:44 +0000742 if (Nodes->getNodeAs<T>(Id)) {
743 ++Count;
744 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
745 Name = Named->getNameAsString();
746 } else if (const NestedNameSpecifier *NNS =
747 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
748 llvm::raw_string_ostream OS(Name);
749 NNS->print(OS, PrintingPolicy(LangOptions()));
750 }
Peter Collingbourne3f0e0402013-11-06 00:27:07 +0000751 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
752 EXPECT_NE(M.end(), I);
753 if (I != M.end())
754 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jaspera267cf62012-10-29 10:14:44 +0000755 return true;
756 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700757 EXPECT_TRUE(M.count(Id) == 0 ||
758 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000759 return false;
760 }
761
Stephen Hines176edba2014-12-01 14:53:08 -0800762 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jasper452abbc2012-10-29 10:48:25 +0000763 return run(Nodes);
764 }
765
Daniel Jaspera267cf62012-10-29 10:14:44 +0000766private:
767 const std::string Id;
768 const int ExpectedCount;
769 int Count;
770 const std::string ExpectedName;
771 std::string Name;
772};
773
774TEST(HasDescendant, MatchesDescendantTypes) {
775 EXPECT_TRUE(matches("void f() { int i = 3; }",
776 decl(hasDescendant(loc(builtinType())))));
777 EXPECT_TRUE(matches("void f() { int i = 3; }",
778 stmt(hasDescendant(builtinType()))));
779
780 EXPECT_TRUE(matches("void f() { int i = 3; }",
781 stmt(hasDescendant(loc(builtinType())))));
782 EXPECT_TRUE(matches("void f() { int i = 3; }",
783 stmt(hasDescendant(qualType(builtinType())))));
784
785 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
786 stmt(hasDescendant(isInteger()))));
787
788 EXPECT_TRUE(matchAndVerifyResultTrue(
789 "void f() { int a; float c; int d; int e; }",
790 functionDecl(forEachDescendant(
791 varDecl(hasDescendant(isInteger())).bind("x"))),
792 new VerifyIdIsBoundTo<Decl>("x", 3)));
793}
794
795TEST(HasDescendant, MatchesDescendantsOfTypes) {
796 EXPECT_TRUE(matches("void f() { int*** i; }",
797 qualType(hasDescendant(builtinType()))));
798 EXPECT_TRUE(matches("void f() { int*** i; }",
799 qualType(hasDescendant(
800 pointerType(pointee(builtinType()))))));
801 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikie5be093c2013-02-18 19:04:16 +0000802 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jaspera267cf62012-10-29 10:14:44 +0000803
804 EXPECT_TRUE(matchAndVerifyResultTrue(
805 "void f() { int*** i; }",
806 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
807 new VerifyIdIsBoundTo<Type>("x", 2)));
808}
809
810TEST(Has, MatchesChildrenOfTypes) {
811 EXPECT_TRUE(matches("int i;",
812 varDecl(hasName("i"), has(isInteger()))));
813 EXPECT_TRUE(notMatches("int** i;",
814 varDecl(hasName("i"), has(isInteger()))));
815 EXPECT_TRUE(matchAndVerifyResultTrue(
816 "int (*f)(float, int);",
817 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
818 new VerifyIdIsBoundTo<QualType>("x", 2)));
819}
820
821TEST(Has, MatchesChildTypes) {
822 EXPECT_TRUE(matches(
823 "int* i;",
824 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
825 EXPECT_TRUE(notMatches(
826 "int* i;",
827 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
828}
829
Stephen Hines176edba2014-12-01 14:53:08 -0800830TEST(ValueDecl, Matches) {
831 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
832 valueDecl(hasType(asString("enum EnumType")))));
833 EXPECT_TRUE(matches("void FunctionDecl();",
834 valueDecl(hasType(asString("void (void)")))));
835}
836
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000837TEST(Enum, DoesNotMatchClasses) {
838 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
839}
840
841TEST(Enum, MatchesEnums) {
842 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
843}
844
845TEST(EnumConstant, Matches) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000846 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000847 EXPECT_TRUE(matches("enum X{ A };", Matcher));
848 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
849 EXPECT_TRUE(notMatches("enum X {};", Matcher));
850}
851
Manuel Klimek4da21662012-07-06 05:48:52 +0000852TEST(StatementMatcher, Has) {
853 StatementMatcher HasVariableI =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000854 expr(hasType(pointsTo(recordDecl(hasName("X")))),
855 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000856
857 EXPECT_TRUE(matches(
858 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
859 EXPECT_TRUE(notMatches(
860 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
861}
862
863TEST(StatementMatcher, HasDescendant) {
864 StatementMatcher HasDescendantVariableI =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000865 expr(hasType(pointsTo(recordDecl(hasName("X")))),
866 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000867
868 EXPECT_TRUE(matches(
869 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
870 HasDescendantVariableI));
871 EXPECT_TRUE(notMatches(
872 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
873 HasDescendantVariableI));
874}
875
876TEST(TypeMatcher, MatchesClassType) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000877 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000878
879 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
880 EXPECT_TRUE(notMatches("class A {};", TypeA));
881
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000882 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000883
884 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
885 TypeDerivedFromA));
886 EXPECT_TRUE(notMatches("class A {};", TypeA));
887
888 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000889 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000890
891 EXPECT_TRUE(
892 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
893}
894
Manuel Klimek4da21662012-07-06 05:48:52 +0000895TEST(Matcher, BindMatchedNodes) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000896 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000897
898 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera7564432012-09-13 13:11:25 +0000899 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000900
901 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera7564432012-09-13 13:11:25 +0000902 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000903
904 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000905 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000906
907 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
908 TypeAHasClassB,
Daniel Jaspera7564432012-09-13 13:11:25 +0000909 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000910
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000911 StatementMatcher MethodX =
912 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek4da21662012-07-06 05:48:52 +0000913
914 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
915 MethodX,
Daniel Jaspera7564432012-09-13 13:11:25 +0000916 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000917}
918
919TEST(Matcher, BindTheSameNameInAlternatives) {
920 StatementMatcher matcher = anyOf(
921 binaryOperator(hasOperatorName("+"),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000922 hasLHS(expr().bind("x")),
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000923 hasRHS(integerLiteral(equals(0)))),
924 binaryOperator(hasOperatorName("+"),
925 hasLHS(integerLiteral(equals(0))),
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000926 hasRHS(expr().bind("x"))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000927
928 EXPECT_TRUE(matchAndVerifyResultTrue(
929 // The first branch of the matcher binds x to 0 but then fails.
930 // The second branch binds x to f() and succeeds.
931 "int f() { return 0 + f(); }",
932 matcher,
Daniel Jaspera7564432012-09-13 13:11:25 +0000933 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000934}
935
Manuel Klimek66341c52012-08-30 19:41:06 +0000936TEST(Matcher, BindsIDForMemoizedResults) {
937 // Using the same matcher in two match expressions will make memoization
938 // kick in.
939 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
940 EXPECT_TRUE(matchAndVerifyResultTrue(
941 "class A { class B { class X {}; }; };",
942 DeclarationMatcher(anyOf(
943 recordDecl(hasName("A"), hasDescendant(ClassX)),
944 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera7564432012-09-13 13:11:25 +0000945 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimek66341c52012-08-30 19:41:06 +0000946}
947
Daniel Jasper189f2e42012-12-03 15:43:25 +0000948TEST(HasDeclaration, HasDeclarationOfEnumType) {
949 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
950 expr(hasType(pointsTo(
951 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
952}
953
Edwin Vaneb45083d2013-02-25 14:32:42 +0000954TEST(HasDeclaration, HasGetDeclTraitTest) {
955 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
956 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
957 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
958}
959
Edwin Vane52380602013-02-19 17:14:34 +0000960TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
961 EXPECT_TRUE(matches("typedef int X; X a;",
962 varDecl(hasName("a"),
963 hasType(typedefType(hasDeclaration(decl()))))));
964
965 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
966}
967
Edwin Vane3abf7782013-02-25 14:49:29 +0000968TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
969 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
970 varDecl(hasType(templateSpecializationType(
971 hasDeclaration(namedDecl(hasName("A"))))))));
972}
973
Manuel Klimek4da21662012-07-06 05:48:52 +0000974TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000975 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000976 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000977 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000978 EXPECT_TRUE(
979 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000980 expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000981 EXPECT_TRUE(
982 matches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000983 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000984}
985
986TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000987 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek4da21662012-07-06 05:48:52 +0000988 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000989 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000990 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000991 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000992 EXPECT_TRUE(
993 matches("class X {}; void y() { X *x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000994 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek4da21662012-07-06 05:48:52 +0000995}
996
997TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +0000998 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +0000999 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001000 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001001 EXPECT_TRUE(
1002 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001003 expr(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001004}
1005
1006TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001007 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek4da21662012-07-06 05:48:52 +00001008 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001009 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001010 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001011 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001012}
1013
Manuel Klimek1a68afd2013-06-20 13:08:29 +00001014TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1015 EXPECT_TRUE(matches("int x;",
1016 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1017
1018 // Make sure we don't crash on implicit constructors.
1019 EXPECT_TRUE(notMatches("class X {}; X x;",
1020 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1021}
1022
Manuel Klimek4da21662012-07-06 05:48:52 +00001023TEST(Matcher, Call) {
1024 // FIXME: Do we want to overload Call() to directly take
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001025 // Matcher<Decl>, too?
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001026 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001027
1028 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1029 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1030
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001031 StatementMatcher MethodOnY =
1032 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001033
1034 EXPECT_TRUE(
1035 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1036 MethodOnY));
1037 EXPECT_TRUE(
1038 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1039 MethodOnY));
1040 EXPECT_TRUE(
1041 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1042 MethodOnY));
1043 EXPECT_TRUE(
1044 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1045 MethodOnY));
1046 EXPECT_TRUE(
1047 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1048 MethodOnY));
1049
1050 StatementMatcher MethodOnYPointer =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001051 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001052
1053 EXPECT_TRUE(
1054 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1055 MethodOnYPointer));
1056 EXPECT_TRUE(
1057 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1058 MethodOnYPointer));
1059 EXPECT_TRUE(
1060 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1061 MethodOnYPointer));
1062 EXPECT_TRUE(
1063 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1064 MethodOnYPointer));
1065 EXPECT_TRUE(
1066 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1067 MethodOnYPointer));
1068}
1069
Daniel Jasper31f7c082012-10-01 13:40:41 +00001070TEST(Matcher, Lambda) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001071 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper31f7c082012-10-01 13:40:41 +00001072 lambdaExpr()));
1073}
1074
1075TEST(Matcher, ForRange) {
Daniel Jasper1a00fee2012-10-01 15:05:34 +00001076 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1077 "void f() { for (auto &a : as); }",
Daniel Jasper31f7c082012-10-01 13:40:41 +00001078 forRangeStmt()));
1079 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1080 forRangeStmt()));
1081}
1082
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001083TEST(Matcher, SubstNonTypeTemplateParm) {
1084 EXPECT_FALSE(matches("template<int N>\n"
1085 "struct A { static const int n = 0; };\n"
1086 "struct B : public A<42> {};",
1087 substNonTypeTemplateParmExpr()));
1088 EXPECT_TRUE(matches("template<int N>\n"
1089 "struct A { static const int n = N; };\n"
1090 "struct B : public A<42> {};",
1091 substNonTypeTemplateParmExpr()));
1092}
1093
Daniel Jasper31f7c082012-10-01 13:40:41 +00001094TEST(Matcher, UserDefinedLiteral) {
1095 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1096 " return i + 1;"
1097 "}"
1098 "char c = 'a'_inc;",
1099 userDefinedLiteral()));
1100}
1101
Daniel Jasperb54b7642012-09-20 14:12:57 +00001102TEST(Matcher, FlowControl) {
1103 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1104 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1105 continueStmt()));
1106 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1107 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1108 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1109}
1110
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001111TEST(HasType, MatchesAsString) {
1112 EXPECT_TRUE(
1113 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001114 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001115 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001116 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001117 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001118 fieldDecl(hasType(asString("ns::A")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001119 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
Stephen Hines651f13c2014-04-23 16:59:28 -07001120 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001121}
1122
Manuel Klimek4da21662012-07-06 05:48:52 +00001123TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001124 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001125 // Unary operator
1126 EXPECT_TRUE(matches("class Y { }; "
1127 "bool operator!(Y x) { return false; }; "
1128 "Y y; bool c = !y;", OpCall));
1129 // No match -- special operators like "new", "delete"
1130 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1131 // we need to figure out include paths in the test.
1132 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1133 // "class Y { }; "
1134 // "void *operator new(size_t size) { return 0; } "
1135 // "Y *y = new Y;", OpCall));
1136 EXPECT_TRUE(notMatches("class Y { }; "
1137 "void operator delete(void *p) { } "
1138 "void a() {Y *y = new Y; delete y;}", OpCall));
1139 // Binary operator
1140 EXPECT_TRUE(matches("class Y { }; "
1141 "bool operator&&(Y x, Y y) { return true; }; "
1142 "Y a; Y b; bool c = a && b;",
1143 OpCall));
1144 // No match -- normal operator, not an overloaded one.
1145 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1146 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1147}
1148
1149TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1150 StatementMatcher OpCallAndAnd =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001151 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek4da21662012-07-06 05:48:52 +00001152 EXPECT_TRUE(matches("class Y { }; "
1153 "bool operator&&(Y x, Y y) { return true; }; "
1154 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1155 StatementMatcher OpCallLessLess =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001156 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek4da21662012-07-06 05:48:52 +00001157 EXPECT_TRUE(notMatches("class Y { }; "
1158 "bool operator&&(Y x, Y y) { return true; }; "
1159 "Y a; Y b; bool c = a && b;",
1160 OpCallLessLess));
Stephen Hines176edba2014-12-01 14:53:08 -08001161 StatementMatcher OpStarCall =
1162 operatorCallExpr(hasOverloadedOperatorName("*"));
1163 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1164 OpStarCall));
Edwin Vane6a19a972013-03-06 17:02:57 +00001165 DeclarationMatcher ClassWithOpStar =
1166 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1167 EXPECT_TRUE(matches("class Y { int operator*(); };",
1168 ClassWithOpStar));
1169 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1170 ClassWithOpStar)) ;
Stephen Hines176edba2014-12-01 14:53:08 -08001171 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1172 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1173 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek4da21662012-07-06 05:48:52 +00001174}
1175
Daniel Jasper278057f2012-11-15 03:29:05 +00001176TEST(Matcher, NestedOverloadedOperatorCalls) {
1177 EXPECT_TRUE(matchAndVerifyResultTrue(
1178 "class Y { }; "
1179 "Y& operator&&(Y& x, Y& y) { return x; }; "
1180 "Y a; Y b; Y c; Y d = a && b && c;",
1181 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1182 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1183 EXPECT_TRUE(matches(
1184 "class Y { }; "
1185 "Y& operator&&(Y& x, Y& y) { return x; }; "
1186 "Y a; Y b; Y c; Y d = a && b && c;",
1187 operatorCallExpr(hasParent(operatorCallExpr()))));
1188 EXPECT_TRUE(matches(
1189 "class Y { }; "
1190 "Y& operator&&(Y& x, Y& y) { return x; }; "
1191 "Y a; Y b; Y c; Y d = a && b && c;",
1192 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1193}
1194
Manuel Klimek4da21662012-07-06 05:48:52 +00001195TEST(Matcher, ThisPointerType) {
Manuel Klimek9f174082012-07-24 13:37:29 +00001196 StatementMatcher MethodOnY =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001197 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001198
1199 EXPECT_TRUE(
1200 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1201 MethodOnY));
1202 EXPECT_TRUE(
1203 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1204 MethodOnY));
1205 EXPECT_TRUE(
1206 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1207 MethodOnY));
1208 EXPECT_TRUE(
1209 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1210 MethodOnY));
1211 EXPECT_TRUE(
1212 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1213 MethodOnY));
1214
1215 EXPECT_TRUE(matches(
1216 "class Y {"
1217 " public: virtual void x();"
1218 "};"
1219 "class X : public Y {"
1220 " public: virtual void x();"
1221 "};"
1222 "void z() { X *x; x->Y::x(); }", MethodOnY));
1223}
1224
1225TEST(Matcher, VariableUsage) {
1226 StatementMatcher Reference =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001227 declRefExpr(to(
1228 varDecl(hasInitializer(
1229 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001230
1231 EXPECT_TRUE(matches(
1232 "class Y {"
1233 " public:"
1234 " bool x() const;"
1235 "};"
1236 "void z(const Y &y) {"
1237 " bool b = y.x();"
1238 " if (b) {}"
1239 "}", Reference));
1240
1241 EXPECT_TRUE(notMatches(
1242 "class Y {"
1243 " public:"
1244 " bool x() const;"
1245 "};"
1246 "void z(const Y &y) {"
1247 " bool b = y.x();"
1248 "}", Reference));
1249}
1250
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001251TEST(Matcher, VarDecl_Storage) {
1252 auto M = varDecl(hasName("X"), hasLocalStorage());
1253 EXPECT_TRUE(matches("void f() { int X; }", M));
1254 EXPECT_TRUE(notMatches("int X;", M));
1255 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1256
1257 M = varDecl(hasName("X"), hasGlobalStorage());
1258 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1259 EXPECT_TRUE(matches("int X;", M));
1260 EXPECT_TRUE(matches("void f() { static int X; }", M));
1261}
1262
Manuel Klimek8cb9bf52012-12-04 14:42:08 +00001263TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper9bd28092012-07-30 05:03:25 +00001264 EXPECT_TRUE(matches(
1265 "void f(int i) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001266 varDecl(hasName("i"))));
Daniel Jasper9bd28092012-07-30 05:03:25 +00001267}
1268
Manuel Klimek4da21662012-07-06 05:48:52 +00001269TEST(Matcher, CalledVariable) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001270 StatementMatcher CallOnVariableY =
1271 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001272
1273 EXPECT_TRUE(matches(
1274 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1275 EXPECT_TRUE(matches(
1276 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1277 EXPECT_TRUE(matches(
1278 "class Y { public: void x(); };"
1279 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1280 EXPECT_TRUE(matches(
1281 "class Y { public: void x(); };"
1282 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1283 EXPECT_TRUE(notMatches(
1284 "class Y { public: void x(); };"
1285 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1286 CallOnVariableY));
1287}
1288
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001289TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1290 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1291 unaryExprOrTypeTraitExpr()));
1292 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1293 alignOfExpr(anything())));
1294 // FIXME: Uncomment once alignof is enabled.
1295 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1296 // unaryExprOrTypeTraitExpr()));
1297 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1298 // sizeOfExpr()));
1299}
1300
1301TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1302 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1303 hasArgumentOfType(asString("int")))));
1304 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1305 hasArgumentOfType(asString("float")))));
1306 EXPECT_TRUE(matches(
1307 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001308 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001309 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001310 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001311}
1312
Manuel Klimek4da21662012-07-06 05:48:52 +00001313TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001314 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001315}
1316
1317TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001318 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001319}
1320
1321TEST(MemberExpression, MatchesVariable) {
1322 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001323 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001324 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001325 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001326 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001327 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001328}
1329
1330TEST(MemberExpression, MatchesStaticVariable) {
1331 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001332 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001333 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001334 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001335 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001336 memberExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00001337}
1338
Daniel Jasper6a124492012-07-12 08:50:38 +00001339TEST(IsInteger, MatchesIntegers) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001340 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1341 EXPECT_TRUE(matches(
1342 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1343 callExpr(hasArgument(0, declRefExpr(
1344 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper6a124492012-07-12 08:50:38 +00001345}
1346
1347TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001348 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00001349 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001350 callExpr(hasArgument(0, declRefExpr(
1351 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper6a124492012-07-12 08:50:38 +00001352}
1353
Manuel Klimek4da21662012-07-06 05:48:52 +00001354TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1355 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001356 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001357 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001358 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001359 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001360 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001361}
1362
1363TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1364 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001365 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001366 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001367 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001368 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001369 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001370}
1371
1372TEST(IsArrow, MatchesMemberCallsViaArrow) {
1373 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001374 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001375 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001376 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001377 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001378 memberExpr(isArrow())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001379}
1380
1381TEST(Callee, MatchesDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001382 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001383
1384 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1385 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1386}
1387
1388TEST(Callee, MatchesMemberExpressions) {
1389 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001390 callExpr(callee(memberExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001391 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001392 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001393}
1394
1395TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001396 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001397
1398 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1399 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1400
Stephen Hines651f13c2014-04-23 16:59:28 -07001401 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1402 llvm::Triple::Win32) {
1403 // FIXME: Make this work for MSVC.
1404 // Dependent contexts, but a non-dependent call.
1405 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1406 CallFunctionF));
1407 EXPECT_TRUE(
1408 matches("void f(); template <int N> struct S { void g() { f(); } };",
1409 CallFunctionF));
1410 }
Manuel Klimek4da21662012-07-06 05:48:52 +00001411
1412 // Depedent calls don't match.
1413 EXPECT_TRUE(
1414 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1415 CallFunctionF));
1416 EXPECT_TRUE(
1417 notMatches("void f(int);"
1418 "template <typename T> struct S { void g(T t) { f(t); } };",
1419 CallFunctionF));
1420}
1421
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001422TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1423 EXPECT_TRUE(
1424 matches("template <typename T> void f(T t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001425 functionTemplateDecl(hasName("f"))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001426}
1427
1428TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1429 EXPECT_TRUE(
1430 notMatches("void f(double d); void f(int t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001431 functionTemplateDecl(hasName("f"))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001432}
1433
1434TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1435 EXPECT_TRUE(
1436 notMatches("void g(); template <typename T> void f(T t) {}"
1437 "template <> void f(int t) { g(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001438 functionTemplateDecl(hasName("f"),
1439 hasDescendant(declRefExpr(to(
1440 functionDecl(hasName("g"))))))));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00001441}
1442
Manuel Klimek4da21662012-07-06 05:48:52 +00001443TEST(Matcher, Argument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001444 StatementMatcher CallArgumentY = callExpr(
1445 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001446
1447 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1448 EXPECT_TRUE(
1449 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1450 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1451
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001452 StatementMatcher WrongIndex = callExpr(
1453 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001454 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1455}
1456
1457TEST(Matcher, AnyArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001458 StatementMatcher CallArgumentY = callExpr(
1459 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001460 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1461 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1462 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1463}
1464
1465TEST(Matcher, ArgumentCount) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001466 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00001467
1468 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1469 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1470 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1471}
1472
Daniel Jasper36e29d62012-12-04 11:54:27 +00001473TEST(Matcher, ParameterCount) {
1474 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1475 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1476 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1477 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1478 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1479}
1480
Manuel Klimek4da21662012-07-06 05:48:52 +00001481TEST(Matcher, References) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001482 DeclarationMatcher ReferenceClassX = varDecl(
1483 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001484 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1485 ReferenceClassX));
1486 EXPECT_TRUE(
1487 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Han4b6730d2013-09-11 15:53:29 +00001488 // The match here is on the implicit copy constructor code for
1489 // class X, not on code 'X x = y'.
Manuel Klimek4da21662012-07-06 05:48:52 +00001490 EXPECT_TRUE(
Michael Han4b6730d2013-09-11 15:53:29 +00001491 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1492 EXPECT_TRUE(
1493 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek4da21662012-07-06 05:48:52 +00001494 EXPECT_TRUE(
1495 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1496}
1497
Edwin Vane6a19a972013-03-06 17:02:57 +00001498TEST(QualType, hasCanonicalType) {
1499 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1500 "int a;"
1501 "int_ref b = a;",
1502 varDecl(hasType(qualType(referenceType())))));
1503 EXPECT_TRUE(
1504 matches("typedef int &int_ref;"
1505 "int a;"
1506 "int_ref b = a;",
1507 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1508}
1509
Edwin Vane7b69cd02013-04-02 18:15:55 +00001510TEST(QualType, hasLocalQualifiers) {
1511 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1512 varDecl(hasType(hasLocalQualifiers()))));
1513 EXPECT_TRUE(matches("int *const j = nullptr;",
1514 varDecl(hasType(hasLocalQualifiers()))));
1515 EXPECT_TRUE(matches("int *volatile k;",
1516 varDecl(hasType(hasLocalQualifiers()))));
1517 EXPECT_TRUE(notMatches("int m;",
1518 varDecl(hasType(hasLocalQualifiers()))));
1519}
1520
Manuel Klimek4da21662012-07-06 05:48:52 +00001521TEST(HasParameter, CallsInnerMatcher) {
1522 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001523 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001524 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001525 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001526}
1527
1528TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1529 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001530 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001531}
1532
1533TEST(HasType, MatchesParameterVariableTypesStrictly) {
1534 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001535 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001536 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001537 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001538 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001539 methodDecl(hasParameter(0,
1540 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001541 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001542 methodDecl(hasParameter(0,
1543 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001544}
1545
1546TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1547 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001548 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001549 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001550 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001551}
1552
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001553TEST(Returns, MatchesReturnTypes) {
1554 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001555 functionDecl(returns(asString("int")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001556 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001557 functionDecl(returns(asString("float")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001558 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001559 functionDecl(returns(hasDeclaration(
1560 recordDecl(hasName("Y")))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001561}
1562
Daniel Jasper8cc7efa2012-08-15 18:52:19 +00001563TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001564 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1565 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1566 functionDecl(isExternC())));
1567 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasper8cc7efa2012-08-15 18:52:19 +00001568}
1569
Stephen Hines176edba2014-12-01 14:53:08 -08001570TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1571 EXPECT_TRUE(
1572 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1573 EXPECT_TRUE(matches("void Func() = delete;",
1574 functionDecl(hasName("Func"), isDeleted())));
1575}
1576
Manuel Klimek4da21662012-07-06 05:48:52 +00001577TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1578 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001579 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001580}
1581
1582TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1583 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001584 methodDecl(hasAnyParameter(hasType(pointsTo(
1585 recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001586}
1587
Stephen Hines651f13c2014-04-23 16:59:28 -07001588TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek4da21662012-07-06 05:48:52 +00001589 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001590 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001591 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001592 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001593}
1594
Daniel Jasper371f9392012-08-01 08:40:24 +00001595TEST(Matcher, MatchesClassTemplateSpecialization) {
1596 EXPECT_TRUE(matches("template<typename T> struct A {};"
1597 "template<> struct A<int> {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001598 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001599 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001600 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001601 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001602 classTemplateSpecializationDecl()));
Daniel Jasper371f9392012-08-01 08:40:24 +00001603}
1604
Manuel Klimek1a68afd2013-06-20 13:08:29 +00001605TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1606 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1607 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1608}
1609
1610TEST(ParmVarDecl, MatchesParmVars) {
1611 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1612 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1613}
1614
Daniel Jasper371f9392012-08-01 08:40:24 +00001615TEST(Matcher, MatchesTypeTemplateArgument) {
1616 EXPECT_TRUE(matches(
1617 "template<typename T> struct B {};"
1618 "B<int> b;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001619 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper371f9392012-08-01 08:40:24 +00001620 asString("int"))))));
1621}
1622
1623TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1624 EXPECT_TRUE(matches(
1625 "struct B { int next; };"
1626 "template<int(B::*next_ptr)> struct A {};"
1627 "A<&B::next> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001628 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1629 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasperaaa8e452012-09-29 15:55:18 +00001630
1631 EXPECT_TRUE(notMatches(
1632 "template <typename T> struct A {};"
1633 "A<int> a;",
1634 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1635 refersToDeclaration(decl())))));
Stephen Hines651f13c2014-04-23 16:59:28 -07001636
1637 EXPECT_TRUE(matches(
1638 "struct B { int next; };"
1639 "template<int(B::*next_ptr)> struct A {};"
1640 "A<&B::next> a;",
1641 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1642 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1643
1644 EXPECT_TRUE(notMatches(
1645 "template <typename T> struct A {};"
1646 "A<int> a;",
1647 templateSpecializationType(hasAnyTemplateArgument(
1648 refersToDeclaration(decl())))));
Daniel Jasper371f9392012-08-01 08:40:24 +00001649}
1650
1651TEST(Matcher, MatchesSpecificArgument) {
1652 EXPECT_TRUE(matches(
1653 "template<typename T, typename U> class A {};"
1654 "A<bool, int> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001655 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper371f9392012-08-01 08:40:24 +00001656 1, refersToType(asString("int"))))));
1657 EXPECT_TRUE(notMatches(
1658 "template<typename T, typename U> class A {};"
1659 "A<int, bool> a;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001660 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper371f9392012-08-01 08:40:24 +00001661 1, refersToType(asString("int"))))));
Stephen Hines651f13c2014-04-23 16:59:28 -07001662
1663 EXPECT_TRUE(matches(
1664 "template<typename T, typename U> class A {};"
1665 "A<bool, int> a;",
1666 templateSpecializationType(hasTemplateArgument(
1667 1, refersToType(asString("int"))))));
1668 EXPECT_TRUE(notMatches(
1669 "template<typename T, typename U> class A {};"
1670 "A<int, bool> a;",
1671 templateSpecializationType(hasTemplateArgument(
1672 1, refersToType(asString("int"))))));
Daniel Jasper371f9392012-08-01 08:40:24 +00001673}
1674
Stephen Hines176edba2014-12-01 14:53:08 -08001675TEST(TemplateArgument, Matches) {
1676 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1677 classTemplateSpecializationDecl(
1678 hasAnyTemplateArgument(templateArgument()))));
1679 EXPECT_TRUE(matches(
1680 "template<typename T> struct C {}; C<int> c;",
1681 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1682}
1683
1684TEST(TemplateArgumentCountIs, Matches) {
1685 EXPECT_TRUE(
1686 matches("template<typename T> struct C {}; C<int> c;",
1687 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1688 EXPECT_TRUE(
1689 notMatches("template<typename T> struct C {}; C<int> c;",
1690 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1691
1692 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1693 templateSpecializationType(templateArgumentCountIs(1))));
1694 EXPECT_TRUE(
1695 notMatches("template<typename T> struct C {}; C<int> c;",
1696 templateSpecializationType(templateArgumentCountIs(2))));
1697}
1698
1699TEST(IsIntegral, Matches) {
1700 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1701 classTemplateSpecializationDecl(
1702 hasAnyTemplateArgument(isIntegral()))));
1703 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1704 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1705 templateArgument(isIntegral())))));
1706}
1707
1708TEST(RefersToIntegralType, Matches) {
1709 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1710 classTemplateSpecializationDecl(
1711 hasAnyTemplateArgument(refersToIntegralType(
1712 asString("int"))))));
1713 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1714 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1715 refersToIntegralType(asString("int"))))));
1716}
1717
1718TEST(EqualsIntegralValue, Matches) {
1719 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1720 classTemplateSpecializationDecl(
1721 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1722 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1723 classTemplateSpecializationDecl(
1724 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1725 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1726 classTemplateSpecializationDecl(
1727 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1728 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1729 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1730 equalsIntegralValue("0042")))));
1731}
1732
Daniel Jasperf3197e92013-02-25 12:02:08 +00001733TEST(Matcher, MatchesAccessSpecDecls) {
1734 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1735 EXPECT_TRUE(
1736 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1737 EXPECT_TRUE(
1738 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1739 EXPECT_TRUE(
1740 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1741
1742 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1743}
1744
Edwin Vane5771a2f2013-04-09 20:46:36 +00001745TEST(Matcher, MatchesVirtualMethod) {
1746 EXPECT_TRUE(matches("class X { virtual int f(); };",
1747 methodDecl(isVirtual(), hasName("::X::f"))));
1748 EXPECT_TRUE(notMatches("class X { int f(); };",
1749 methodDecl(isVirtual())));
1750}
1751
Stephen Hines651f13c2014-04-23 16:59:28 -07001752TEST(Matcher, MatchesPureMethod) {
1753 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1754 methodDecl(isPure(), hasName("::X::f"))));
1755 EXPECT_TRUE(notMatches("class X { int f(); };",
1756 methodDecl(isPure())));
1757}
1758
Edwin Vane32a6ebc2013-05-09 17:00:17 +00001759TEST(Matcher, MatchesConstMethod) {
1760 EXPECT_TRUE(matches("struct A { void foo() const; };",
1761 methodDecl(isConst())));
1762 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1763 methodDecl(isConst())));
1764}
1765
Edwin Vane5771a2f2013-04-09 20:46:36 +00001766TEST(Matcher, MatchesOverridingMethod) {
1767 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1768 "class Y : public X { int f(); };",
1769 methodDecl(isOverride(), hasName("::Y::f"))));
1770 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1771 "class Y : public X { int f(); };",
1772 methodDecl(isOverride(), hasName("::X::f"))));
1773 EXPECT_TRUE(notMatches("class X { int f(); }; "
1774 "class Y : public X { int f(); };",
1775 methodDecl(isOverride())));
1776 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1777 methodDecl(isOverride())));
1778}
1779
Manuel Klimek4da21662012-07-06 05:48:52 +00001780TEST(Matcher, ConstructorCall) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001781 StatementMatcher Constructor = constructExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001782
1783 EXPECT_TRUE(
1784 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1785 EXPECT_TRUE(
1786 matches("class X { public: X(); }; void x() { X x = X(); }",
1787 Constructor));
1788 EXPECT_TRUE(
1789 matches("class X { public: X(int); }; void x() { X x = 0; }",
1790 Constructor));
1791 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1792}
1793
1794TEST(Matcher, ConstructorArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001795 StatementMatcher Constructor = constructExpr(
1796 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001797
1798 EXPECT_TRUE(
1799 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1800 Constructor));
1801 EXPECT_TRUE(
1802 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1803 Constructor));
1804 EXPECT_TRUE(
1805 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1806 Constructor));
1807 EXPECT_TRUE(
1808 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1809 Constructor));
1810
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001811 StatementMatcher WrongIndex = constructExpr(
1812 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001813 EXPECT_TRUE(
1814 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1815 WrongIndex));
1816}
1817
1818TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001819 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00001820
1821 EXPECT_TRUE(
1822 matches("class X { public: X(int); }; void x() { X x(0); }",
1823 Constructor1Arg));
1824 EXPECT_TRUE(
1825 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1826 Constructor1Arg));
1827 EXPECT_TRUE(
1828 matches("class X { public: X(int); }; void x() { X x = 0; }",
1829 Constructor1Arg));
1830 EXPECT_TRUE(
1831 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1832 Constructor1Arg));
1833}
1834
Stephen Hines651f13c2014-04-23 16:59:28 -07001835TEST(Matcher, ConstructorListInitialization) {
1836 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1837
1838 EXPECT_TRUE(
1839 matches("class X { public: X(int); }; void x() { X x{0}; }",
1840 ConstructorListInit));
1841 EXPECT_FALSE(
1842 matches("class X { public: X(int); }; void x() { X x(0); }",
1843 ConstructorListInit));
1844}
1845
Manuel Klimek70b9db92012-10-23 10:40:50 +00001846TEST(Matcher,ThisExpr) {
1847 EXPECT_TRUE(
1848 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1849 EXPECT_TRUE(
1850 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1851}
1852
Manuel Klimek4da21662012-07-06 05:48:52 +00001853TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00001854 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00001855
1856 std::string ClassString = "class string { public: string(); ~string(); }; ";
1857
1858 EXPECT_TRUE(
1859 matches(ClassString +
1860 "string GetStringByValue();"
1861 "void FunctionTakesString(string s);"
1862 "void run() { FunctionTakesString(GetStringByValue()); }",
1863 TempExpression));
1864
1865 EXPECT_TRUE(
1866 notMatches(ClassString +
1867 "string* GetStringPointer(); "
1868 "void FunctionTakesStringPtr(string* s);"
1869 "void run() {"
1870 " string* s = GetStringPointer();"
1871 " FunctionTakesStringPtr(GetStringPointer());"
1872 " FunctionTakesStringPtr(s);"
1873 "}",
1874 TempExpression));
1875
1876 EXPECT_TRUE(
1877 notMatches("class no_dtor {};"
1878 "no_dtor GetObjByValue();"
1879 "void ConsumeObj(no_dtor param);"
1880 "void run() { ConsumeObj(GetObjByValue()); }",
1881 TempExpression));
1882}
1883
Sam Panzere16acd32012-08-24 22:04:44 +00001884TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1885 std::string ClassString =
1886 "class string { public: string(); int length(); }; ";
1887
1888 EXPECT_TRUE(
1889 matches(ClassString +
1890 "string GetStringByValue();"
1891 "void FunctionTakesString(string s);"
1892 "void run() { FunctionTakesString(GetStringByValue()); }",
1893 materializeTemporaryExpr()));
1894
1895 EXPECT_TRUE(
1896 notMatches(ClassString +
1897 "string* GetStringPointer(); "
1898 "void FunctionTakesStringPtr(string* s);"
1899 "void run() {"
1900 " string* s = GetStringPointer();"
1901 " FunctionTakesStringPtr(GetStringPointer());"
1902 " FunctionTakesStringPtr(s);"
1903 "}",
1904 materializeTemporaryExpr()));
1905
1906 EXPECT_TRUE(
1907 notMatches(ClassString +
1908 "string GetStringByValue();"
1909 "void run() { int k = GetStringByValue().length(); }",
1910 materializeTemporaryExpr()));
1911
1912 EXPECT_TRUE(
1913 notMatches(ClassString +
1914 "string GetStringByValue();"
1915 "void run() { GetStringByValue(); }",
1916 materializeTemporaryExpr()));
1917}
1918
Manuel Klimek4da21662012-07-06 05:48:52 +00001919TEST(ConstructorDeclaration, SimpleCase) {
1920 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001921 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001922 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001923 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001924}
1925
1926TEST(ConstructorDeclaration, IsImplicit) {
1927 // This one doesn't match because the constructor is not added by the
1928 // compiler (it is not needed).
1929 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001930 constructorDecl(isImplicit())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001931 // The compiler added the implicit default constructor.
1932 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001933 constructorDecl(isImplicit())));
Manuel Klimek4da21662012-07-06 05:48:52 +00001934 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001935 constructorDecl(unless(isImplicit()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001936 // The compiler added an implicit assignment operator.
1937 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1938 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001939}
1940
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001941TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1942 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001943 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001944}
1945
1946TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001947 EXPECT_TRUE(notMatches("class Foo {};",
1948 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00001949}
1950
Manuel Klimek4da21662012-07-06 05:48:52 +00001951TEST(HasAnyConstructorInitializer, SimpleCase) {
1952 EXPECT_TRUE(notMatches(
1953 "class Foo { Foo() { } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001954 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001955 EXPECT_TRUE(matches(
1956 "class Foo {"
1957 " Foo() : foo_() { }"
1958 " int foo_;"
1959 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001960 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001961}
1962
1963TEST(HasAnyConstructorInitializer, ForField) {
1964 static const char Code[] =
1965 "class Baz { };"
1966 "class Foo {"
1967 " Foo() : foo_() { }"
1968 " Baz foo_;"
1969 " Baz bar_;"
1970 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001971 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1972 forField(hasType(recordDecl(hasName("Baz"))))))));
1973 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001974 forField(hasName("foo_"))))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001975 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1976 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00001977}
1978
1979TEST(HasAnyConstructorInitializer, WithInitializer) {
1980 static const char Code[] =
1981 "class Foo {"
1982 " Foo() : foo_(0) { }"
1983 " int foo_;"
1984 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001985 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001986 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001987 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00001988 withInitializer(integerLiteral(equals(1)))))));
1989}
1990
1991TEST(HasAnyConstructorInitializer, IsWritten) {
1992 static const char Code[] =
1993 "struct Bar { Bar(){} };"
1994 "class Foo {"
1995 " Foo() : foo_() { }"
1996 " Bar foo_;"
1997 " Bar bar_;"
1998 "};";
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00001999 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00002000 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002001 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00002002 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002003 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek4da21662012-07-06 05:48:52 +00002004 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2005}
2006
2007TEST(Matcher, NewExpression) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002008 StatementMatcher New = newExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00002009
2010 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2011 EXPECT_TRUE(
2012 matches("class X { public: X(); }; void x() { new X(); }", New));
2013 EXPECT_TRUE(
2014 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2015 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2016}
2017
2018TEST(Matcher, NewExpressionArgument) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002019 StatementMatcher New = constructExpr(
2020 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002021
2022 EXPECT_TRUE(
2023 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2024 New));
2025 EXPECT_TRUE(
2026 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2027 New));
2028 EXPECT_TRUE(
2029 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2030 New));
2031
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002032 StatementMatcher WrongIndex = constructExpr(
2033 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002034 EXPECT_TRUE(
2035 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2036 WrongIndex));
2037}
2038
2039TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002040 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek4da21662012-07-06 05:48:52 +00002041
2042 EXPECT_TRUE(
2043 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2044 EXPECT_TRUE(
2045 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2046 New));
2047}
2048
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002049TEST(Matcher, DeleteExpression) {
2050 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002051 deleteExpr()));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002052}
2053
Manuel Klimek4da21662012-07-06 05:48:52 +00002054TEST(Matcher, DefaultArgument) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002055 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek4da21662012-07-06 05:48:52 +00002056
2057 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2058 EXPECT_TRUE(
2059 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2060 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2061}
2062
2063TEST(Matcher, StringLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002064 StatementMatcher Literal = stringLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00002065 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2066 // wide string
2067 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2068 // with escaped characters
2069 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2070 // no matching -- though the data type is the same, there is no string literal
2071 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2072}
2073
2074TEST(Matcher, CharacterLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002075 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00002076 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2077 // wide character
2078 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2079 // wide character, Hex encoded, NOT MATCHED!
2080 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2081 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2082}
2083
2084TEST(Matcher, IntegerLiterals) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002085 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek4da21662012-07-06 05:48:52 +00002086 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2087 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2088 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2089 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2090
2091 // Non-matching cases (character literals, float and double)
2092 EXPECT_TRUE(notMatches("int i = L'a';",
2093 HasIntLiteral)); // this is actually a character
2094 // literal cast to int
2095 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2096 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2097 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2098}
2099
Daniel Jasperc5ae7172013-07-26 18:52:58 +00002100TEST(Matcher, FloatLiterals) {
2101 StatementMatcher HasFloatLiteral = floatLiteral();
2102 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2103 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2104 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2105 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2106 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
2107
2108 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
2109}
2110
Daniel Jasper31f7c082012-10-01 13:40:41 +00002111TEST(Matcher, NullPtrLiteral) {
2112 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2113}
2114
Daniel Jasperb54b7642012-09-20 14:12:57 +00002115TEST(Matcher, AsmStatement) {
2116 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2117}
2118
Manuel Klimek4da21662012-07-06 05:48:52 +00002119TEST(Matcher, Conditions) {
2120 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2121
2122 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2123 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2124 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2125 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2126 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2127}
2128
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002129TEST(IfStmt, ChildTraversalMatchers) {
2130 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2131 ifStmt(hasThen(boolLiteral(equals(true))))));
2132 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2133 ifStmt(hasThen(boolLiteral(equals(true))))));
2134 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2135 ifStmt(hasElse(boolLiteral(equals(true))))));
2136 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2137 ifStmt(hasElse(boolLiteral(equals(true))))));
2138}
2139
Manuel Klimek4da21662012-07-06 05:48:52 +00002140TEST(MatchBinaryOperator, HasOperatorName) {
2141 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2142
2143 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2144 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2145}
2146
2147TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2148 StatementMatcher OperatorTrueFalse =
2149 binaryOperator(hasLHS(boolLiteral(equals(true))),
2150 hasRHS(boolLiteral(equals(false))));
2151
2152 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2153 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2154 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2155}
2156
2157TEST(MatchBinaryOperator, HasEitherOperand) {
2158 StatementMatcher HasOperand =
2159 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2160
2161 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2162 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2163 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2164}
2165
2166TEST(Matcher, BinaryOperatorTypes) {
2167 // Integration test that verifies the AST provides all binary operators in
2168 // a way we expect.
2169 // FIXME: Operator ','
2170 EXPECT_TRUE(
2171 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2172 EXPECT_TRUE(
2173 matches("bool b; bool c = (b = true);",
2174 binaryOperator(hasOperatorName("="))));
2175 EXPECT_TRUE(
2176 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2177 EXPECT_TRUE(
2178 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2179 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2180 EXPECT_TRUE(
2181 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2182 EXPECT_TRUE(
2183 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2184 EXPECT_TRUE(
2185 matches("int i = 1; int j = (i <<= 2);",
2186 binaryOperator(hasOperatorName("<<="))));
2187 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2188 EXPECT_TRUE(
2189 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2190 EXPECT_TRUE(
2191 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2192 EXPECT_TRUE(
2193 matches("int i = 1; int j = (i >>= 2);",
2194 binaryOperator(hasOperatorName(">>="))));
2195 EXPECT_TRUE(
2196 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2197 EXPECT_TRUE(
2198 matches("int i = 42; int j = (i ^= 42);",
2199 binaryOperator(hasOperatorName("^="))));
2200 EXPECT_TRUE(
2201 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2202 EXPECT_TRUE(
2203 matches("int i = 42; int j = (i %= 42);",
2204 binaryOperator(hasOperatorName("%="))));
2205 EXPECT_TRUE(
2206 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2207 EXPECT_TRUE(
2208 matches("bool b = true && false;",
2209 binaryOperator(hasOperatorName("&&"))));
2210 EXPECT_TRUE(
2211 matches("bool b = true; bool c = (b &= false);",
2212 binaryOperator(hasOperatorName("&="))));
2213 EXPECT_TRUE(
2214 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2215 EXPECT_TRUE(
2216 matches("bool b = true || false;",
2217 binaryOperator(hasOperatorName("||"))));
2218 EXPECT_TRUE(
2219 matches("bool b = true; bool c = (b |= false);",
2220 binaryOperator(hasOperatorName("|="))));
2221 EXPECT_TRUE(
2222 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2223 EXPECT_TRUE(
2224 matches("int i = 42; int j = (i *= 23);",
2225 binaryOperator(hasOperatorName("*="))));
2226 EXPECT_TRUE(
2227 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2228 EXPECT_TRUE(
2229 matches("int i = 42; int j = (i /= 23);",
2230 binaryOperator(hasOperatorName("/="))));
2231 EXPECT_TRUE(
2232 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2233 EXPECT_TRUE(
2234 matches("int i = 42; int j = (i += 23);",
2235 binaryOperator(hasOperatorName("+="))));
2236 EXPECT_TRUE(
2237 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2238 EXPECT_TRUE(
2239 matches("int i = 42; int j = (i -= 23);",
2240 binaryOperator(hasOperatorName("-="))));
2241 EXPECT_TRUE(
2242 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2243 binaryOperator(hasOperatorName("->*"))));
2244 EXPECT_TRUE(
2245 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2246 binaryOperator(hasOperatorName(".*"))));
2247
2248 // Member expressions as operators are not supported in matches.
2249 EXPECT_TRUE(
2250 notMatches("struct A { void x(A *a) { a->x(this); } };",
2251 binaryOperator(hasOperatorName("->"))));
2252
2253 // Initializer assignments are not represented as operator equals.
2254 EXPECT_TRUE(
2255 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2256
2257 // Array indexing is not represented as operator.
2258 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2259
2260 // Overloaded operators do not match at all.
2261 EXPECT_TRUE(notMatches(
2262 "struct A { bool operator&&(const A &a) const { return false; } };"
2263 "void x() { A a, b; a && b; }",
2264 binaryOperator()));
2265}
2266
2267TEST(MatchUnaryOperator, HasOperatorName) {
2268 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2269
2270 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2271 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2272}
2273
2274TEST(MatchUnaryOperator, HasUnaryOperand) {
2275 StatementMatcher OperatorOnFalse =
2276 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2277
2278 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2279 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2280}
2281
2282TEST(Matcher, UnaryOperatorTypes) {
2283 // Integration test that verifies the AST provides all unary operators in
2284 // a way we expect.
2285 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2286 EXPECT_TRUE(
2287 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2288 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2289 EXPECT_TRUE(
2290 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2291 EXPECT_TRUE(
2292 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2293 EXPECT_TRUE(
2294 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2295 EXPECT_TRUE(
2296 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2297 EXPECT_TRUE(
2298 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2299 EXPECT_TRUE(
2300 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2301 EXPECT_TRUE(
2302 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2303
2304 // We don't match conversion operators.
2305 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2306
2307 // Function calls are not represented as operator.
2308 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2309
2310 // Overloaded operators do not match at all.
2311 // FIXME: We probably want to add that.
2312 EXPECT_TRUE(notMatches(
2313 "struct A { bool operator!() const { return false; } };"
2314 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2315}
2316
2317TEST(Matcher, ConditionalOperator) {
2318 StatementMatcher Conditional = conditionalOperator(
2319 hasCondition(boolLiteral(equals(true))),
2320 hasTrueExpression(boolLiteral(equals(false))));
2321
2322 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2323 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2324 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2325
2326 StatementMatcher ConditionalFalse = conditionalOperator(
2327 hasFalseExpression(boolLiteral(equals(false))));
2328
2329 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2330 EXPECT_TRUE(
2331 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2332}
2333
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002334TEST(ArraySubscriptMatchers, ArraySubscripts) {
2335 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2336 arraySubscriptExpr()));
2337 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2338 arraySubscriptExpr()));
2339}
2340
2341TEST(ArraySubscriptMatchers, ArrayIndex) {
2342 EXPECT_TRUE(matches(
2343 "int i[2]; void f() { i[1] = 1; }",
2344 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2345 EXPECT_TRUE(matches(
2346 "int i[2]; void f() { 1[i] = 1; }",
2347 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2348 EXPECT_TRUE(notMatches(
2349 "int i[2]; void f() { i[1] = 1; }",
2350 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2351}
2352
2353TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2354 EXPECT_TRUE(matches(
2355 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002356 arraySubscriptExpr(hasBase(implicitCastExpr(
2357 hasSourceExpression(declRefExpr()))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002358}
2359
Manuel Klimek4da21662012-07-06 05:48:52 +00002360TEST(Matcher, HasNameSupportsNamespaces) {
2361 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002362 recordDecl(hasName("a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002363 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002364 recordDecl(hasName("::a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002365 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002366 recordDecl(hasName("b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002367 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002368 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002369 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002370 recordDecl(hasName("c::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002371 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002372 recordDecl(hasName("a::c::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002373 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002374 recordDecl(hasName("a::b::A"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002375 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002376 recordDecl(hasName("::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002377 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002378 recordDecl(hasName("::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002379 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002380 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002381 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002382 recordDecl(hasName("a+b::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002383 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002384 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002385}
2386
2387TEST(Matcher, HasNameSupportsOuterClasses) {
2388 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002389 matches("class A { class B { class C; }; };",
2390 recordDecl(hasName("A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002391 EXPECT_TRUE(
2392 matches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002393 recordDecl(hasName("::A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002394 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002395 matches("class A { class B { class C; }; };",
2396 recordDecl(hasName("B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002397 EXPECT_TRUE(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002398 matches("class A { class B { class C; }; };",
2399 recordDecl(hasName("C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002400 EXPECT_TRUE(
2401 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002402 recordDecl(hasName("c::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002403 EXPECT_TRUE(
2404 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002405 recordDecl(hasName("A::c::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002406 EXPECT_TRUE(
2407 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002408 recordDecl(hasName("A::B::A"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002409 EXPECT_TRUE(
2410 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002411 recordDecl(hasName("::C"))));
2412 EXPECT_TRUE(
2413 notMatches("class A { class B { class C; }; };",
2414 recordDecl(hasName("::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002415 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002416 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002417 EXPECT_TRUE(
2418 notMatches("class A { class B { class C; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002419 recordDecl(hasName("A+B::C"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002420}
2421
2422TEST(Matcher, IsDefinition) {
2423 DeclarationMatcher DefinitionOfClassA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002424 recordDecl(hasName("A"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002425 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2426 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2427
2428 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002429 varDecl(hasName("a"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002430 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2431 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2432
2433 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002434 methodDecl(hasName("a"), isDefinition());
Manuel Klimek4da21662012-07-06 05:48:52 +00002435 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2436 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2437}
2438
2439TEST(Matcher, OfClass) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002440 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek4da21662012-07-06 05:48:52 +00002441 ofClass(hasName("X")))));
2442
2443 EXPECT_TRUE(
2444 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2445 EXPECT_TRUE(
2446 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2447 Constructor));
2448 EXPECT_TRUE(
2449 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2450 Constructor));
2451}
2452
2453TEST(Matcher, VisitsTemplateInstantiations) {
2454 EXPECT_TRUE(matches(
2455 "class A { public: void x(); };"
2456 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002457 "void f() { B<A> b; b.y(); }",
2458 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002459
2460 EXPECT_TRUE(matches(
2461 "class A { public: void x(); };"
2462 "class C {"
2463 " public:"
2464 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2465 "};"
2466 "void f() {"
2467 " C::B<A> b; b.y();"
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002468 "}",
2469 recordDecl(hasName("C"),
2470 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002471}
2472
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002473TEST(Matcher, HandlesNullQualTypes) {
2474 // FIXME: Add a Type matcher so we can replace uses of this
2475 // variable with Type(True())
2476 const TypeMatcher AnyType = anything();
2477
2478 // We don't really care whether this matcher succeeds; we're testing that
2479 // it completes without crashing.
2480 EXPECT_TRUE(matches(
2481 "struct A { };"
2482 "template <typename T>"
2483 "void f(T t) {"
2484 " T local_t(t /* this becomes a null QualType in the AST */);"
2485 "}"
2486 "void g() {"
2487 " f(0);"
2488 "}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002489 expr(hasType(TypeMatcher(
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002490 anyOf(
2491 TypeMatcher(hasDeclaration(anything())),
2492 pointsTo(AnyType),
2493 references(AnyType)
2494 // Other QualType matchers should go here.
2495 ))))));
2496}
2497
Manuel Klimek4da21662012-07-06 05:48:52 +00002498// For testing AST_MATCHER_P().
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00002499AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002500 // Make sure all special variables are used: node, match_finder,
2501 // bound_nodes_builder, and the parameter named 'AMatcher'.
2502 return AMatcher.matches(Node, Finder, Builder);
2503}
2504
2505TEST(AstMatcherPMacro, Works) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002506 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002507
2508 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002509 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002510
2511 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002512 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002513
2514 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002515 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002516}
2517
2518AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenef7eb022013-06-21 15:51:31 +00002519 polymorphicHas,
2520 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2521 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002522 return Finder->matchesChildOf(
Manuel Klimeka78d0d62012-09-05 12:12:07 +00002523 Node, AMatcher, Builder,
Manuel Klimek4da21662012-07-06 05:48:52 +00002524 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2525 ASTMatchFinder::BK_First);
2526}
2527
2528TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002529 DeclarationMatcher HasClassB =
2530 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek4da21662012-07-06 05:48:52 +00002531
2532 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002533 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002534
2535 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002536 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002537
2538 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera7564432012-09-13 13:11:25 +00002539 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002540
2541 StatementMatcher StatementHasClassB =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002542 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek4da21662012-07-06 05:48:52 +00002543
2544 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2545}
2546
2547TEST(For, FindsForLoops) {
2548 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2549 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper1a00fee2012-10-01 15:05:34 +00002550 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2551 "void f() { for (auto &a : as); }",
Daniel Jasper31f7c082012-10-01 13:40:41 +00002552 forStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002553}
2554
Daniel Jasper6a124492012-07-12 08:50:38 +00002555TEST(For, ForLoopInternals) {
2556 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2557 forStmt(hasCondition(anything()))));
2558 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2559 forStmt(hasLoopInit(anything()))));
2560}
2561
Stephen Hines651f13c2014-04-23 16:59:28 -07002562TEST(For, ForRangeLoopInternals) {
2563 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2564 forRangeStmt(hasLoopVariable(anything()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002565 EXPECT_TRUE(matches(
2566 "void f(){ int a[] {1, 2}; for (int i : a); }",
2567 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Stephen Hines651f13c2014-04-23 16:59:28 -07002568}
2569
Daniel Jasper6a124492012-07-12 08:50:38 +00002570TEST(For, NegativeForLoopInternals) {
2571 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002572 forStmt(hasCondition(expr()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002573 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2574 forStmt(hasLoopInit(anything()))));
2575}
2576
Manuel Klimek4da21662012-07-06 05:48:52 +00002577TEST(For, ReportsNoFalsePositives) {
2578 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2579 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2580}
2581
2582TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002583 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2584 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2585 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002586}
2587
2588TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2589 // It's not a compound statement just because there's "{}" in the source
2590 // text. This is an AST search, not grep.
2591 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002592 compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002593 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002594 compoundStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002595}
2596
Daniel Jasper6a124492012-07-12 08:50:38 +00002597TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek4da21662012-07-06 05:48:52 +00002598 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002599 forStmt(hasBody(compoundStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002600 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002601 forStmt(hasBody(compoundStmt()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002602 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002603 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper6a124492012-07-12 08:50:38 +00002604 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002605 doStmt(hasBody(compoundStmt()))));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002606 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2607 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002608}
2609
2610TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2611 // The simplest case: every compound statement is in a function
2612 // definition, and the function body itself must be a compound
2613 // statement.
2614 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002615 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002616}
2617
2618TEST(HasAnySubstatement, IsNotRecursive) {
2619 // It's really "has any immediate substatement".
2620 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002621 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002622}
2623
2624TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2625 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002626 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002627}
2628
2629TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2630 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002631 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002632}
2633
2634TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2635 EXPECT_TRUE(matches("void f() { }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002636 compoundStmt(statementCountIs(0))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002637 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002638 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002639}
2640
2641TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2642 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002643 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002644 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002645 compoundStmt(statementCountIs(0))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002646 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002647 compoundStmt(statementCountIs(2))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002648}
2649
2650TEST(StatementCountIs, WorksWithMultipleStatements) {
2651 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002652 compoundStmt(statementCountIs(3))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002653}
2654
2655TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2656 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002657 compoundStmt(statementCountIs(1))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002658 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002659 compoundStmt(statementCountIs(2))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002660 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002661 compoundStmt(statementCountIs(3))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002662 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002663 compoundStmt(statementCountIs(4))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002664}
2665
2666TEST(Member, WorksInSimplestCase) {
2667 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002668 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002669}
2670
2671TEST(Member, DoesNotMatchTheBaseExpression) {
2672 // Don't pick out the wrong part of the member expression, this should
2673 // be checking the member (name) only.
2674 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002675 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002676}
2677
2678TEST(Member, MatchesInMemberFunctionCall) {
2679 EXPECT_TRUE(matches("void f() {"
2680 " struct { void first() {}; } s;"
2681 " s.first();"
2682 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002683 memberExpr(member(hasName("first")))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002684}
2685
Daniel Jasperc711af22012-10-23 15:46:39 +00002686TEST(Member, MatchesMember) {
2687 EXPECT_TRUE(matches(
2688 "struct A { int i; }; void f() { A a; a.i = 2; }",
2689 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2690 EXPECT_TRUE(notMatches(
2691 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2692 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2693}
2694
Daniel Jasperf3197e92013-02-25 12:02:08 +00002695TEST(Member, UnderstandsAccess) {
2696 EXPECT_TRUE(matches(
2697 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2698 EXPECT_TRUE(notMatches(
2699 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2700 EXPECT_TRUE(notMatches(
2701 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2702
2703 EXPECT_TRUE(notMatches(
2704 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2705 EXPECT_TRUE(notMatches(
2706 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2707 EXPECT_TRUE(matches(
2708 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2709
2710 EXPECT_TRUE(notMatches(
2711 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2712 EXPECT_TRUE(matches("class A { protected: int i; };",
2713 fieldDecl(isProtected(), hasName("i"))));
2714 EXPECT_TRUE(notMatches(
2715 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2716
2717 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2718 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2719 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2720 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2721}
2722
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002723TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper31f7c082012-10-01 13:40:41 +00002724 // Fails in C++11 mode
2725 EXPECT_TRUE(matchesConditionally(
2726 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2727 "class X { void *operator new(std::size_t); };",
2728 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002729
2730 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002731 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002732
Daniel Jasper31f7c082012-10-01 13:40:41 +00002733 // Fails in C++11 mode
2734 EXPECT_TRUE(matchesConditionally(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002735 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2736 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper31f7c082012-10-01 13:40:41 +00002737 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko671a0452012-08-18 00:29:27 +00002738}
2739
Manuel Klimek4da21662012-07-06 05:48:52 +00002740TEST(HasObjectExpression, DoesNotMatchMember) {
2741 EXPECT_TRUE(notMatches(
2742 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002743 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002744}
2745
2746TEST(HasObjectExpression, MatchesBaseOfVariable) {
2747 EXPECT_TRUE(matches(
2748 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002749 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002750 EXPECT_TRUE(matches(
2751 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002752 memberExpr(hasObjectExpression(
2753 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002754}
2755
2756TEST(HasObjectExpression,
2757 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2758 EXPECT_TRUE(matches(
2759 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002760 memberExpr(hasObjectExpression(
2761 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002762 EXPECT_TRUE(matches(
2763 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002764 memberExpr(hasObjectExpression(
2765 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002766}
2767
2768TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002769 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2770 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2771 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2772 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002773}
2774
2775TEST(Field, MatchesField) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002776 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002777}
2778
2779TEST(IsConstQualified, MatchesConstInt) {
2780 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002781 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002782}
2783
2784TEST(IsConstQualified, MatchesConstPointer) {
2785 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002786 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002787}
2788
2789TEST(IsConstQualified, MatchesThroughTypedef) {
2790 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002791 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002792 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002793 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002794}
2795
2796TEST(IsConstQualified, DoesNotMatchInappropriately) {
2797 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002798 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002799 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002800 varDecl(hasType(isConstQualified()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002801}
2802
Sam Panzer089e5b32012-08-16 16:58:10 +00002803TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002804 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2805 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2806 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2807 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002808}
2809TEST(CastExpression, MatchesImplicitCasts) {
2810 // This test creates an implicit cast from int to char.
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002811 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002812 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002813 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002814}
2815
2816TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002817 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2818 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2819 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2820 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer089e5b32012-08-16 16:58:10 +00002821}
2822
Manuel Klimek4da21662012-07-06 05:48:52 +00002823TEST(ReinterpretCast, MatchesSimpleCase) {
2824 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002825 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002826}
2827
2828TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002829 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002830 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002831 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002832 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002833 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002834 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2835 "B b;"
2836 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002837 reinterpretCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002838}
2839
2840TEST(FunctionalCast, MatchesSimpleCase) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002841 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek4da21662012-07-06 05:48:52 +00002842 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002843 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002844}
2845
2846TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002847 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek4da21662012-07-06 05:48:52 +00002848 EXPECT_TRUE(
2849 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002850 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002851 EXPECT_TRUE(
2852 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002853 functionalCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002854}
2855
2856TEST(DynamicCast, MatchesSimpleCase) {
2857 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2858 "B b;"
2859 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002860 dynamicCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002861}
2862
2863TEST(StaticCast, MatchesSimpleCase) {
2864 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002865 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002866}
2867
2868TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002869 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002870 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002871 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002872 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002873 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002874 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2875 "B b;"
2876 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002877 staticCastExpr()));
Manuel Klimek4da21662012-07-06 05:48:52 +00002878}
2879
Daniel Jaspere6d2a962012-09-18 13:36:17 +00002880TEST(CStyleCast, MatchesSimpleCase) {
2881 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2882}
2883
2884TEST(CStyleCast, DoesNotMatchOtherCasts) {
2885 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2886 "char q, *r = const_cast<char*>(&q);"
2887 "void* s = reinterpret_cast<char*>(&s);"
2888 "struct B { virtual ~B() {} }; struct D : B {};"
2889 "B b;"
2890 "D* t = dynamic_cast<D*>(&b);",
2891 cStyleCastExpr()));
2892}
2893
Manuel Klimek4da21662012-07-06 05:48:52 +00002894TEST(HasDestinationType, MatchesSimpleCase) {
2895 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002896 staticCastExpr(hasDestinationType(
2897 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00002898}
2899
Sam Panzer089e5b32012-08-16 16:58:10 +00002900TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2901 // This test creates an implicit const cast.
2902 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002903 implicitCastExpr(
2904 hasImplicitDestinationType(isInteger()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002905 // This test creates an implicit array-to-pointer cast.
2906 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002907 implicitCastExpr(hasImplicitDestinationType(
2908 pointsTo(TypeMatcher(anything()))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002909}
2910
2911TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2912 // This test creates an implicit cast from int to char.
2913 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002914 implicitCastExpr(hasImplicitDestinationType(
2915 unless(anything())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002916 // This test creates an implicit array-to-pointer cast.
2917 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00002918 implicitCastExpr(hasImplicitDestinationType(
2919 unless(anything())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002920}
2921
2922TEST(ImplicitCast, MatchesSimpleCase) {
2923 // This test creates an implicit const cast.
2924 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002925 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002926 // This test creates an implicit cast from int to char.
2927 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002928 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002929 // This test creates an implicit array-to-pointer cast.
2930 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002931 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002932}
2933
2934TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002935 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer089e5b32012-08-16 16:58:10 +00002936 // are present, and that it ignores explicit and paren casts.
2937
2938 // These two test cases have no casts.
2939 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002940 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002941 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002942 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002943
2944 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002945 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002946 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002947 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002948
2949 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002950 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002951}
2952
2953TEST(IgnoringImpCasts, MatchesImpCasts) {
2954 // This test checks that ignoringImpCasts matches when implicit casts are
2955 // present and its inner matcher alone does not match.
2956 // Note that this test creates an implicit const cast.
2957 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002958 varDecl(hasInitializer(ignoringImpCasts(
2959 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002960 // This test creates an implict cast from int to char.
2961 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002962 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002963 integerLiteral(equals(0)))))));
2964}
2965
2966TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2967 // These tests verify that ignoringImpCasts does not match if the inner
2968 // matcher does not match.
2969 // Note that the first test creates an implicit const cast.
2970 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002971 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002972 unless(anything()))))));
2973 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002974 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00002975 unless(anything()))))));
2976
2977 // These tests verify that ignoringImplictCasts does not look through explicit
2978 // casts or parentheses.
2979 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002980 varDecl(hasInitializer(ignoringImpCasts(
2981 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002982 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002983 varDecl(hasInitializer(ignoringImpCasts(
2984 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002985 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002986 varDecl(hasInitializer(ignoringImpCasts(
2987 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002988 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002989 varDecl(hasInitializer(ignoringImpCasts(
2990 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002991}
2992
2993TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2994 // This test verifies that expressions that do not have implicit casts
2995 // still match the inner matcher.
2996 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00002997 varDecl(hasInitializer(ignoringImpCasts(
2998 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00002999}
3000
3001TEST(IgnoringParenCasts, MatchesParenCasts) {
3002 // This test checks that ignoringParenCasts matches when parentheses and/or
3003 // casts are present and its inner matcher alone does not match.
3004 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003005 varDecl(hasInitializer(ignoringParenCasts(
3006 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003007 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003008 varDecl(hasInitializer(ignoringParenCasts(
3009 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003010
3011 // This test creates an implict cast from int to char in addition to the
3012 // parentheses.
3013 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003014 varDecl(hasInitializer(ignoringParenCasts(
3015 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003016
3017 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003018 varDecl(hasInitializer(ignoringParenCasts(
3019 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003020 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003021 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003022 integerLiteral(equals(0)))))));
3023}
3024
3025TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3026 // This test verifies that expressions that do not have any casts still match.
3027 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003028 varDecl(hasInitializer(ignoringParenCasts(
3029 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003030}
3031
3032TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3033 // These tests verify that ignoringImpCasts does not match if the inner
3034 // matcher does not match.
3035 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003036 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003037 unless(anything()))))));
3038
3039 // This test creates an implicit cast from int to char in addition to the
3040 // parentheses.
3041 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003042 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003043 unless(anything()))))));
3044
3045 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003046 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003047 unless(anything()))))));
3048}
3049
3050TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3051 // This test checks that ignoringParenAndImpCasts matches when
3052 // parentheses and/or implicit casts are present and its inner matcher alone
3053 // does not match.
3054 // Note that this test creates an implicit const cast.
3055 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003056 varDecl(hasInitializer(ignoringParenImpCasts(
3057 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003058 // This test creates an implicit cast from int to char.
3059 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003060 varDecl(hasInitializer(ignoringParenImpCasts(
3061 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003062}
3063
3064TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3065 // This test verifies that expressions that do not have parentheses or
3066 // implicit casts still match.
3067 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003068 varDecl(hasInitializer(ignoringParenImpCasts(
3069 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003070 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003071 varDecl(hasInitializer(ignoringParenImpCasts(
3072 integerLiteral(equals(0)))))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003073}
3074
3075TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3076 // These tests verify that ignoringParenImpCasts does not match if
3077 // the inner matcher does not match.
3078 // This test creates an implicit cast.
3079 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003080 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer089e5b32012-08-16 16:58:10 +00003081 unless(anything()))))));
3082 // These tests verify that ignoringParenAndImplictCasts does not look
3083 // through explicit casts.
3084 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003085 varDecl(hasInitializer(ignoringParenImpCasts(
3086 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003087 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003088 varDecl(hasInitializer(ignoringParenImpCasts(
3089 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003090 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003091 varDecl(hasInitializer(ignoringParenImpCasts(
3092 integerLiteral())))));
Sam Panzer089e5b32012-08-16 16:58:10 +00003093}
3094
Manuel Klimek715c9562012-07-25 10:02:02 +00003095TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek4da21662012-07-06 05:48:52 +00003096 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3097 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003098 implicitCastExpr(
3099 hasSourceExpression(constructExpr()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003100}
3101
Manuel Klimek715c9562012-07-25 10:02:02 +00003102TEST(HasSourceExpression, MatchesExplicitCasts) {
3103 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003104 explicitCastExpr(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003105 hasSourceExpression(hasDescendant(
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003106 expr(integerLiteral()))))));
Manuel Klimek715c9562012-07-25 10:02:02 +00003107}
3108
Manuel Klimek4da21662012-07-06 05:48:52 +00003109TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003110 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00003111}
3112
3113TEST(Statement, MatchesCompoundStatments) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003114 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00003115}
3116
3117TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003118 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00003119}
3120
3121TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003122 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek4da21662012-07-06 05:48:52 +00003123}
3124
Stephen Hines651f13c2014-04-23 16:59:28 -07003125TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3126 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3127 "const Foo f = Foo();",
3128 varDecl(hasInitializer(exprWithCleanups()))));
3129 EXPECT_FALSE(matches("struct Foo { };"
3130 "const Foo f = Foo();",
3131 varDecl(hasInitializer(exprWithCleanups()))));
3132}
3133
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003134TEST(InitListExpression, MatchesInitListExpression) {
3135 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3136 initListExpr(hasType(asString("int [2]")))));
3137 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003138 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003139}
3140
3141TEST(UsingDeclaration, MatchesUsingDeclarations) {
3142 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3143 usingDecl()));
3144}
3145
3146TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3147 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3148 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3149}
3150
3151TEST(UsingDeclaration, MatchesSpecificTarget) {
3152 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3153 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003154 hasTargetDecl(functionDecl())))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003155 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3156 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003157 hasTargetDecl(functionDecl())))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003158}
3159
3160TEST(UsingDeclaration, ThroughUsingDeclaration) {
3161 EXPECT_TRUE(matches(
3162 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003163 declRefExpr(throughUsingDecl(anything()))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003164 EXPECT_TRUE(notMatches(
3165 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003166 declRefExpr(throughUsingDecl(anything()))));
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +00003167}
3168
Stephen Hines176edba2014-12-01 14:53:08 -08003169TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3170 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3171 usingDirectiveDecl()));
3172 EXPECT_FALSE(
3173 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3174}
3175
Sam Panzer425f41b2012-08-16 17:20:59 +00003176TEST(SingleDecl, IsSingleDecl) {
3177 StatementMatcher SingleDeclStmt =
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003178 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003179 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3180 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3181 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3182 SingleDeclStmt));
3183}
3184
3185TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003186 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzer425f41b2012-08-16 17:20:59 +00003187
3188 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003189 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003190 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003191 declStmt(containsDeclaration(0, MatchesInit),
3192 containsDeclaration(1, MatchesInit))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003193 unsigned WrongIndex = 42;
3194 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003195 declStmt(containsDeclaration(WrongIndex,
Sam Panzer425f41b2012-08-16 17:20:59 +00003196 MatchesInit))));
3197}
3198
3199TEST(DeclCount, DeclCountIsCorrect) {
3200 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003201 declStmt(declCountIs(2))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003202 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003203 declStmt(declCountIs(3))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003204 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003205 declStmt(declCountIs(3))));
Sam Panzer425f41b2012-08-16 17:20:59 +00003206}
3207
Manuel Klimek4da21662012-07-06 05:48:52 +00003208TEST(While, MatchesWhileLoops) {
3209 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3210 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3211 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3212}
3213
3214TEST(Do, MatchesDoLoops) {
3215 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3216 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3217}
3218
3219TEST(Do, DoesNotMatchWhileLoops) {
3220 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3221}
3222
3223TEST(SwitchCase, MatchesCase) {
3224 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3225 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3226 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3227 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3228}
3229
Daniel Jasperb54b7642012-09-20 14:12:57 +00003230TEST(SwitchCase, MatchesSwitch) {
3231 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3232 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3233 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3234 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3235}
3236
Peter Collingbourneacf02712013-05-10 11:52:02 +00003237TEST(SwitchCase, MatchesEachCase) {
3238 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3239 switchStmt(forEachSwitchCase(caseStmt()))));
3240 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3241 switchStmt(forEachSwitchCase(caseStmt()))));
3242 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3243 switchStmt(forEachSwitchCase(caseStmt()))));
3244 EXPECT_TRUE(notMatches(
3245 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3246 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3247 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3248 switchStmt(forEachSwitchCase(
3249 caseStmt(hasCaseConstant(integerLiteral()))))));
3250 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3251 switchStmt(forEachSwitchCase(
3252 caseStmt(hasCaseConstant(integerLiteral()))))));
3253 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3254 switchStmt(forEachSwitchCase(
3255 caseStmt(hasCaseConstant(integerLiteral()))))));
3256 EXPECT_TRUE(matchAndVerifyResultTrue(
3257 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3258 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3259 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3260}
3261
Manuel Klimek06963012013-07-19 11:50:54 +00003262TEST(ForEachConstructorInitializer, MatchesInitializers) {
3263 EXPECT_TRUE(matches(
3264 "struct X { X() : i(42), j(42) {} int i, j; };",
3265 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3266}
3267
Daniel Jasperb54b7642012-09-20 14:12:57 +00003268TEST(ExceptionHandling, SimpleCases) {
3269 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3270 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3271 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3272 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3273 throwExpr()));
3274 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3275 throwExpr()));
3276}
3277
Manuel Klimek4da21662012-07-06 05:48:52 +00003278TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3279 EXPECT_TRUE(notMatches(
3280 "void x() { if(true) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003281 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003282 EXPECT_TRUE(notMatches(
3283 "void x() { int x; if((x = 42)) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003284 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003285}
3286
3287TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3288 EXPECT_TRUE(matches(
3289 "void x() { if(int* a = 0) {} }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003290 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003291}
3292
3293TEST(ForEach, BindsOneNode) {
3294 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003295 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003296 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003297}
3298
3299TEST(ForEach, BindsMultipleNodes) {
3300 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003301 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003302 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003303}
3304
3305TEST(ForEach, BindsRecursiveCombinations) {
3306 EXPECT_TRUE(matchAndVerifyResultTrue(
3307 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003308 recordDecl(hasName("C"),
3309 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003310 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003311}
3312
3313TEST(ForEachDescendant, BindsOneNode) {
3314 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003315 recordDecl(hasName("C"),
3316 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003317 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003318}
3319
Daniel Jasper5f684e92012-11-16 18:39:22 +00003320TEST(ForEachDescendant, NestedForEachDescendant) {
3321 DeclarationMatcher m = recordDecl(
3322 isDefinition(), decl().bind("x"), hasName("C"));
3323 EXPECT_TRUE(matchAndVerifyResultTrue(
3324 "class A { class B { class C {}; }; };",
3325 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3326 new VerifyIdIsBoundTo<Decl>("x", "C")));
3327
Manuel Klimek054d0492013-06-19 15:42:45 +00003328 // Check that a partial match of 'm' that binds 'x' in the
3329 // first part of anyOf(m, anything()) will not overwrite the
3330 // binding created by the earlier binding in the hasDescendant.
3331 EXPECT_TRUE(matchAndVerifyResultTrue(
3332 "class A { class B { class C {}; }; };",
3333 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3334 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper5f684e92012-11-16 18:39:22 +00003335}
3336
Manuel Klimek4da21662012-07-06 05:48:52 +00003337TEST(ForEachDescendant, BindsMultipleNodes) {
3338 EXPECT_TRUE(matchAndVerifyResultTrue(
3339 "class C { class D { int x; int y; }; "
3340 " class E { class F { int y; int z; }; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003341 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003342 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003343}
3344
3345TEST(ForEachDescendant, BindsRecursiveCombinations) {
3346 EXPECT_TRUE(matchAndVerifyResultTrue(
3347 "class C { class D { "
3348 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003349 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3350 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003351 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek4da21662012-07-06 05:48:52 +00003352}
3353
Manuel Klimek054d0492013-06-19 15:42:45 +00003354TEST(ForEachDescendant, BindsCombinations) {
3355 EXPECT_TRUE(matchAndVerifyResultTrue(
3356 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3357 "(true) {} }",
3358 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3359 forEachDescendant(whileStmt().bind("while"))),
3360 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3361}
3362
3363TEST(Has, DoesNotDeleteBindings) {
3364 EXPECT_TRUE(matchAndVerifyResultTrue(
3365 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3366 new VerifyIdIsBoundTo<Decl>("x", 1)));
3367}
3368
3369TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3370 // Those matchers cover all the cases where an inner matcher is called
3371 // and there is not a 1:1 relationship between the match of the outer
3372 // matcher and the match of the inner matcher.
3373 // The pattern to look for is:
3374 // ... return InnerMatcher.matches(...); ...
3375 // In which case no special handling is needed.
3376 //
3377 // On the other hand, if there are multiple alternative matches
3378 // (for example forEach*) or matches might be discarded (for example has*)
3379 // the implementation must make sure that the discarded matches do not
3380 // affect the bindings.
3381 // When new such matchers are added, add a test here that:
3382 // - matches a simple node, and binds it as the first thing in the matcher:
3383 // recordDecl(decl().bind("x"), hasName("X")))
3384 // - uses the matcher under test afterwards in a way that not the first
3385 // alternative is matched; for anyOf, that means the first branch
3386 // would need to return false; for hasAncestor, it means that not
3387 // the direct parent matches the inner matcher.
3388
3389 EXPECT_TRUE(matchAndVerifyResultTrue(
3390 "class X { int y; };",
3391 recordDecl(
3392 recordDecl().bind("x"), hasName("::X"),
3393 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3394 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3395 EXPECT_TRUE(matchAndVerifyResultTrue(
3396 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3397 anyOf(unless(anything()), anything())),
3398 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3399 EXPECT_TRUE(matchAndVerifyResultTrue(
3400 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3401 classTemplateSpecializationDecl(
3402 decl().bind("x"),
3403 hasAnyTemplateArgument(refersToType(asString("int")))),
3404 new VerifyIdIsBoundTo<Decl>("x", 1)));
3405 EXPECT_TRUE(matchAndVerifyResultTrue(
3406 "class X { void f(); void g(); };",
3407 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3408 new VerifyIdIsBoundTo<Decl>("x", 1)));
3409 EXPECT_TRUE(matchAndVerifyResultTrue(
3410 "class X { X() : a(1), b(2) {} double a; int b; };",
3411 recordDecl(decl().bind("x"),
3412 has(constructorDecl(
3413 hasAnyConstructorInitializer(forField(hasName("b")))))),
3414 new VerifyIdIsBoundTo<Decl>("x", 1)));
3415 EXPECT_TRUE(matchAndVerifyResultTrue(
3416 "void x(int, int) { x(0, 42); }",
3417 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3418 new VerifyIdIsBoundTo<Expr>("x", 1)));
3419 EXPECT_TRUE(matchAndVerifyResultTrue(
3420 "void x(int, int y) {}",
3421 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3422 new VerifyIdIsBoundTo<Decl>("x", 1)));
3423 EXPECT_TRUE(matchAndVerifyResultTrue(
3424 "void x() { return; if (true) {} }",
3425 functionDecl(decl().bind("x"),
3426 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3427 new VerifyIdIsBoundTo<Decl>("x", 1)));
3428 EXPECT_TRUE(matchAndVerifyResultTrue(
3429 "namespace X { void b(int); void b(); }"
3430 "using X::b;",
3431 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3432 functionDecl(parameterCountIs(1))))),
3433 new VerifyIdIsBoundTo<Decl>("x", 1)));
3434 EXPECT_TRUE(matchAndVerifyResultTrue(
3435 "class A{}; class B{}; class C : B, A {};",
3436 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3437 new VerifyIdIsBoundTo<Decl>("x", 1)));
3438 EXPECT_TRUE(matchAndVerifyResultTrue(
3439 "class A{}; typedef A B; typedef A C; typedef A D;"
3440 "class E : A {};",
3441 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3442 new VerifyIdIsBoundTo<Decl>("x", 1)));
3443 EXPECT_TRUE(matchAndVerifyResultTrue(
3444 "class A { class B { void f() {} }; };",
3445 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3446 new VerifyIdIsBoundTo<Decl>("x", 1)));
3447 EXPECT_TRUE(matchAndVerifyResultTrue(
3448 "template <typename T> struct A { struct B {"
3449 " void f() { if(true) {} }"
3450 "}; };"
3451 "void t() { A<int>::B b; b.f(); }",
3452 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3453 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3454 EXPECT_TRUE(matchAndVerifyResultTrue(
3455 "class A {};",
3456 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3457 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimek06963012013-07-19 11:50:54 +00003458 EXPECT_TRUE(matchAndVerifyResultTrue(
3459 "class A { A() : s(), i(42) {} const char *s; int i; };",
3460 constructorDecl(hasName("::A::A"), decl().bind("x"),
3461 forEachConstructorInitializer(forField(hasName("i")))),
3462 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimek054d0492013-06-19 15:42:45 +00003463}
3464
Daniel Jasper11c98772012-11-11 22:14:55 +00003465TEST(ForEachDescendant, BindsCorrectNodes) {
3466 EXPECT_TRUE(matchAndVerifyResultTrue(
3467 "class C { void f(); int i; };",
3468 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3469 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3470 EXPECT_TRUE(matchAndVerifyResultTrue(
3471 "class C { void f() {} int i; };",
3472 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3473 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3474}
3475
Manuel Klimek152ea0e2013-02-04 10:59:20 +00003476TEST(FindAll, BindsNodeOnMatch) {
3477 EXPECT_TRUE(matchAndVerifyResultTrue(
3478 "class A {};",
3479 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3480 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3481}
3482
3483TEST(FindAll, BindsDescendantNodeOnMatch) {
3484 EXPECT_TRUE(matchAndVerifyResultTrue(
3485 "class A { int a; int b; };",
3486 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3487 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3488}
3489
3490TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3491 EXPECT_TRUE(matchAndVerifyResultTrue(
3492 "class A { int a; int b; };",
3493 recordDecl(hasName("::A"),
3494 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3495 fieldDecl().bind("v"))))),
3496 new VerifyIdIsBoundTo<Decl>("v", 3)));
3497
3498 EXPECT_TRUE(matchAndVerifyResultTrue(
3499 "class A { class B {}; class C {}; };",
3500 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3501 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3502}
3503
Manuel Klimek73876732013-02-04 09:42:38 +00003504TEST(EachOf, TriggersForEachMatch) {
3505 EXPECT_TRUE(matchAndVerifyResultTrue(
3506 "class A { int a; int b; };",
3507 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3508 has(fieldDecl(hasName("b")).bind("v")))),
3509 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3510}
3511
3512TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3513 EXPECT_TRUE(matchAndVerifyResultTrue(
3514 "class A { int a; int c; };",
3515 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3516 has(fieldDecl(hasName("b")).bind("v")))),
3517 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3518 EXPECT_TRUE(matchAndVerifyResultTrue(
3519 "class A { int c; int b; };",
3520 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3521 has(fieldDecl(hasName("b")).bind("v")))),
3522 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3523 EXPECT_TRUE(notMatches(
3524 "class A { int c; int d; };",
3525 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3526 has(fieldDecl(hasName("b")).bind("v"))))));
3527}
Manuel Klimek4da21662012-07-06 05:48:52 +00003528
3529TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3530 // Make sure that we can both match the class by name (::X) and by the type
3531 // the template was instantiated with (via a field).
3532
3533 EXPECT_TRUE(matches(
3534 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003535 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003536
3537 EXPECT_TRUE(matches(
3538 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003539 recordDecl(isTemplateInstantiation(), hasDescendant(
3540 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003541}
3542
3543TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3544 EXPECT_TRUE(matches(
3545 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003546 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek4da21662012-07-06 05:48:52 +00003547 isTemplateInstantiation())));
3548}
3549
3550TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3551 EXPECT_TRUE(matches(
3552 "template <typename T> class X { T t; }; class A {};"
3553 "template class X<A>;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003554 recordDecl(isTemplateInstantiation(), hasDescendant(
3555 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003556}
3557
3558TEST(IsTemplateInstantiation,
3559 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3560 EXPECT_TRUE(matches(
3561 "template <typename T> class X {};"
3562 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003563 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003564}
3565
3566TEST(IsTemplateInstantiation,
3567 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3568 EXPECT_TRUE(matches(
3569 "class A {};"
3570 "class X {"
3571 " template <typename U> class Y { U u; };"
3572 " Y<A> y;"
3573 "};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003574 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003575}
3576
3577TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3578 // FIXME: Figure out whether this makes sense. It doesn't affect the
3579 // normal use case as long as the uppermost instantiation always is marked
3580 // as template instantiation, but it might be confusing as a predicate.
3581 EXPECT_TRUE(matches(
3582 "class A {};"
3583 "template <typename T> class X {"
3584 " template <typename U> class Y { U u; };"
3585 " Y<T> y;"
3586 "}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003587 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek4da21662012-07-06 05:48:52 +00003588}
3589
3590TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3591 EXPECT_TRUE(notMatches(
3592 "template <typename T> class X {}; class A {};"
3593 "template <> class X<A> {}; X<A> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003594 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003595}
3596
3597TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3598 EXPECT_TRUE(notMatches(
3599 "class A {}; class Y { A a; };",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003600 recordDecl(isTemplateInstantiation())));
Manuel Klimek4da21662012-07-06 05:48:52 +00003601}
3602
Stephen Hines176edba2014-12-01 14:53:08 -08003603TEST(IsInstantiated, MatchesInstantiation) {
3604 EXPECT_TRUE(
3605 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3606 recordDecl(isInstantiated())));
3607}
3608
3609TEST(IsInstantiated, NotMatchesDefinition) {
3610 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3611 recordDecl(isInstantiated())));
3612}
3613
3614TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3615 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3616 "class Y { A<int> a; }; Y y;",
3617 declStmt(isInTemplateInstantiation())));
3618}
3619
3620TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3621 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3622 declStmt(isInTemplateInstantiation())));
3623}
3624
3625TEST(IsInstantiated, MatchesFunctionInstantiation) {
3626 EXPECT_TRUE(
3627 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3628 functionDecl(isInstantiated())));
3629}
3630
3631TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3632 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3633 varDecl(isInstantiated())));
3634}
3635
3636TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3637 EXPECT_TRUE(
3638 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3639 declStmt(isInTemplateInstantiation())));
3640}
3641
3642TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3643 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3644 declStmt(isInTemplateInstantiation())));
3645}
3646
3647TEST(IsInTemplateInstantiation, Sharing) {
3648 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3649 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3650 // and makes the matcher behave in non-obvious ways.
3651 EXPECT_TRUE(notMatches(
3652 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3653 Matcher));
3654 EXPECT_TRUE(matches(
3655 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3656 Matcher));
3657}
3658
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003659TEST(IsExplicitTemplateSpecialization,
3660 DoesNotMatchPrimaryTemplate) {
3661 EXPECT_TRUE(notMatches(
3662 "template <typename T> class X {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003663 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003664 EXPECT_TRUE(notMatches(
3665 "template <typename T> void f(T t);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003666 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003667}
3668
3669TEST(IsExplicitTemplateSpecialization,
3670 DoesNotMatchExplicitTemplateInstantiations) {
3671 EXPECT_TRUE(notMatches(
3672 "template <typename T> class X {};"
3673 "template class X<int>; extern template class X<long>;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003674 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003675 EXPECT_TRUE(notMatches(
3676 "template <typename T> void f(T t) {}"
3677 "template void f(int t); extern template void f(long t);",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003678 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003679}
3680
3681TEST(IsExplicitTemplateSpecialization,
3682 DoesNotMatchImplicitTemplateInstantiations) {
3683 EXPECT_TRUE(notMatches(
3684 "template <typename T> class X {}; X<int> x;",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003685 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003686 EXPECT_TRUE(notMatches(
3687 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003688 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003689}
3690
3691TEST(IsExplicitTemplateSpecialization,
3692 MatchesExplicitTemplateSpecializations) {
3693 EXPECT_TRUE(matches(
3694 "template <typename T> class X {};"
3695 "template<> class X<int> {};",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003696 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003697 EXPECT_TRUE(matches(
3698 "template <typename T> void f(T t) {}"
3699 "template<> void f(int t) {}",
Daniel Jasper2dc75ed2012-08-24 05:12:34 +00003700 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenko8456ae62012-08-17 18:42:47 +00003701}
3702
Manuel Klimek579b1202012-09-07 09:26:10 +00003703TEST(HasAncenstor, MatchesDeclarationAncestors) {
3704 EXPECT_TRUE(matches(
3705 "class A { class B { class C {}; }; };",
3706 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3707}
3708
3709TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3710 EXPECT_TRUE(notMatches(
3711 "class A { class B { class C {}; }; };",
3712 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3713}
3714
3715TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3716 EXPECT_TRUE(matches(
3717 "class A { class B { void f() { C c; } class C {}; }; };",
3718 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3719 hasAncestor(recordDecl(hasName("A"))))))));
3720}
3721
3722TEST(HasAncenstor, MatchesStatementAncestors) {
3723 EXPECT_TRUE(matches(
3724 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003725 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek579b1202012-09-07 09:26:10 +00003726}
3727
3728TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3729 EXPECT_TRUE(matches(
3730 "void f() { if (true) { int x = 42; } }",
Daniel Jasper3680b4f2012-09-18 13:09:13 +00003731 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek579b1202012-09-07 09:26:10 +00003732}
3733
3734TEST(HasAncestor, BindsRecursiveCombinations) {
3735 EXPECT_TRUE(matchAndVerifyResultTrue(
3736 "class C { class D { class E { class F { int y; }; }; }; };",
3737 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera7564432012-09-13 13:11:25 +00003738 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek579b1202012-09-07 09:26:10 +00003739}
3740
3741TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3742 EXPECT_TRUE(matchAndVerifyResultTrue(
3743 "class C { class D { class E { class F { int y; }; }; }; };",
3744 fieldDecl(hasAncestor(
3745 decl(
3746 hasDescendant(recordDecl(isDefinition(),
3747 hasAncestor(recordDecl())))
3748 ).bind("d")
3749 )),
Daniel Jaspera7564432012-09-13 13:11:25 +00003750 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek579b1202012-09-07 09:26:10 +00003751}
3752
Manuel Klimek374516c2013-03-14 16:33:21 +00003753TEST(HasAncestor, MatchesClosestAncestor) {
3754 EXPECT_TRUE(matchAndVerifyResultTrue(
3755 "template <typename T> struct C {"
3756 " void f(int) {"
3757 " struct I { void g(T) { int x; } } i; i.g(42);"
3758 " }"
3759 "};"
3760 "template struct C<int>;",
3761 varDecl(hasName("x"),
3762 hasAncestor(functionDecl(hasParameter(
3763 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3764 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3765}
3766
Manuel Klimek579b1202012-09-07 09:26:10 +00003767TEST(HasAncestor, MatchesInTemplateInstantiations) {
3768 EXPECT_TRUE(matches(
3769 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3770 "A<int>::B::C a;",
3771 fieldDecl(hasType(asString("int")),
3772 hasAncestor(recordDecl(hasName("A"))))));
3773}
3774
3775TEST(HasAncestor, MatchesInImplicitCode) {
3776 EXPECT_TRUE(matches(
3777 "struct X {}; struct A { A() {} X x; };",
3778 constructorDecl(
3779 hasAnyConstructorInitializer(withInitializer(expr(
3780 hasAncestor(recordDecl(hasName("A")))))))));
3781}
3782
Daniel Jasperc99a3ad2012-10-22 16:26:51 +00003783TEST(HasParent, MatchesOnlyParent) {
3784 EXPECT_TRUE(matches(
3785 "void f() { if (true) { int x = 42; } }",
3786 compoundStmt(hasParent(ifStmt()))));
3787 EXPECT_TRUE(notMatches(
3788 "void f() { for (;;) { int x = 42; } }",
3789 compoundStmt(hasParent(ifStmt()))));
3790 EXPECT_TRUE(notMatches(
3791 "void f() { if (true) for (;;) { int x = 42; } }",
3792 compoundStmt(hasParent(ifStmt()))));
3793}
3794
Manuel Klimek30ace372012-12-06 14:42:48 +00003795TEST(HasAncestor, MatchesAllAncestors) {
3796 EXPECT_TRUE(matches(
3797 "template <typename T> struct C { static void f() { 42; } };"
3798 "void t() { C<int>::f(); }",
3799 integerLiteral(
3800 equals(42),
3801 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3802 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3803}
3804
3805TEST(HasParent, MatchesAllParents) {
3806 EXPECT_TRUE(matches(
3807 "template <typename T> struct C { static void f() { 42; } };"
3808 "void t() { C<int>::f(); }",
3809 integerLiteral(
3810 equals(42),
3811 hasParent(compoundStmt(hasParent(functionDecl(
3812 hasParent(recordDecl(isTemplateInstantiation())))))))));
3813 EXPECT_TRUE(matches(
3814 "template <typename T> struct C { static void f() { 42; } };"
3815 "void t() { C<int>::f(); }",
3816 integerLiteral(
3817 equals(42),
3818 hasParent(compoundStmt(hasParent(functionDecl(
3819 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3820 EXPECT_TRUE(matches(
3821 "template <typename T> struct C { static void f() { 42; } };"
3822 "void t() { C<int>::f(); }",
3823 integerLiteral(equals(42),
3824 hasParent(compoundStmt(allOf(
3825 hasParent(functionDecl(
3826 hasParent(recordDecl(isTemplateInstantiation())))),
3827 hasParent(functionDecl(hasParent(recordDecl(
3828 unless(isTemplateInstantiation())))))))))));
Manuel Klimek374516c2013-03-14 16:33:21 +00003829 EXPECT_TRUE(
3830 notMatches("template <typename T> struct C { static void f() {} };"
3831 "void t() { C<int>::f(); }",
3832 compoundStmt(hasParent(recordDecl()))));
Manuel Klimek30ace372012-12-06 14:42:48 +00003833}
3834
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003835TEST(HasParent, NoDuplicateParents) {
3836 class HasDuplicateParents : public BoundNodesCallback {
3837 public:
3838 bool run(const BoundNodes *Nodes) override { return false; }
3839 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3840 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3841 std::set<const void *> Parents;
3842 for (const auto &Parent : Context->getParents(*Node)) {
3843 if (!Parents.insert(Parent.getMemoizationData()).second) {
3844 return true;
3845 }
3846 }
3847 return false;
3848 }
3849 };
3850 EXPECT_FALSE(matchAndVerifyResultTrue(
3851 "template <typename T> int Foo() { return 1 + 2; }\n"
3852 "int x = Foo<int>() + Foo<unsigned>();",
3853 stmt().bind("node"), new HasDuplicateParents()));
3854}
3855
Daniel Jasperce620072012-10-17 08:52:59 +00003856TEST(TypeMatching, MatchesTypes) {
3857 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3858}
3859
3860TEST(TypeMatching, MatchesArrayTypes) {
3861 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3862 EXPECT_TRUE(matches("int a[42];", arrayType()));
3863 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3864
3865 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3866 arrayType(hasElementType(builtinType()))));
3867
3868 EXPECT_TRUE(matches(
3869 "int const a[] = { 2, 3 };",
3870 qualType(arrayType(hasElementType(builtinType())))));
3871 EXPECT_TRUE(matches(
3872 "int const a[] = { 2, 3 };",
3873 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3874 EXPECT_TRUE(matches(
3875 "typedef const int T; T x[] = { 1, 2 };",
3876 qualType(isConstQualified(), arrayType())));
3877
3878 EXPECT_TRUE(notMatches(
3879 "int a[] = { 2, 3 };",
3880 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3881 EXPECT_TRUE(notMatches(
3882 "int a[] = { 2, 3 };",
3883 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3884 EXPECT_TRUE(notMatches(
3885 "int const a[] = { 2, 3 };",
3886 qualType(arrayType(hasElementType(builtinType())),
3887 unless(isConstQualified()))));
3888
3889 EXPECT_TRUE(matches("int a[2];",
3890 constantArrayType(hasElementType(builtinType()))));
3891 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3892}
3893
3894TEST(TypeMatching, MatchesComplexTypes) {
3895 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3896 EXPECT_TRUE(matches(
3897 "_Complex float f;",
3898 complexType(hasElementType(builtinType()))));
3899 EXPECT_TRUE(notMatches(
3900 "_Complex float f;",
3901 complexType(hasElementType(isInteger()))));
3902}
3903
3904TEST(TypeMatching, MatchesConstantArrayTypes) {
3905 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3906 EXPECT_TRUE(notMatches(
3907 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3908 constantArrayType(hasElementType(builtinType()))));
3909
3910 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3911 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3912 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3913}
3914
3915TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3916 EXPECT_TRUE(matches(
3917 "template <typename T, int Size> class array { T data[Size]; };",
3918 dependentSizedArrayType()));
3919 EXPECT_TRUE(notMatches(
3920 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3921 dependentSizedArrayType()));
3922}
3923
3924TEST(TypeMatching, MatchesIncompleteArrayType) {
3925 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3926 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3927
3928 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3929 incompleteArrayType()));
3930}
3931
3932TEST(TypeMatching, MatchesVariableArrayType) {
3933 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3934 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3935
3936 EXPECT_TRUE(matches(
3937 "void f(int b) { int a[b]; }",
3938 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3939 varDecl(hasName("b")))))))));
3940}
3941
3942TEST(TypeMatching, MatchesAtomicTypes) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003943 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3944 llvm::Triple::Win32) {
3945 // FIXME: Make this work for MSVC.
3946 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasperce620072012-10-17 08:52:59 +00003947
Stephen Hines651f13c2014-04-23 16:59:28 -07003948 EXPECT_TRUE(matches("_Atomic(int) i;",
3949 atomicType(hasValueType(isInteger()))));
3950 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3951 atomicType(hasValueType(isInteger()))));
3952 }
Daniel Jasperce620072012-10-17 08:52:59 +00003953}
3954
3955TEST(TypeMatching, MatchesAutoTypes) {
3956 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3957 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3958 autoType()));
3959
Richard Smith9b131752013-04-30 21:23:01 +00003960 // FIXME: Matching against the type-as-written can't work here, because the
3961 // type as written was not deduced.
3962 //EXPECT_TRUE(matches("auto a = 1;",
3963 // autoType(hasDeducedType(isInteger()))));
3964 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3965 // autoType(hasDeducedType(isInteger()))));
Daniel Jasperce620072012-10-17 08:52:59 +00003966}
3967
Daniel Jaspera267cf62012-10-29 10:14:44 +00003968TEST(TypeMatching, MatchesFunctionTypes) {
3969 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3970 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3971}
3972
Edwin Vane88be2fd2013-04-01 18:33:34 +00003973TEST(TypeMatching, MatchesParenType) {
3974 EXPECT_TRUE(
3975 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3976 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3977
3978 EXPECT_TRUE(matches(
3979 "int (*ptr_to_func)(int);",
3980 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3981 EXPECT_TRUE(notMatches(
3982 "int (*ptr_to_array)[4];",
3983 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3984}
3985
Daniel Jasperce620072012-10-17 08:52:59 +00003986TEST(TypeMatching, PointerTypes) {
Daniel Jasper1802daf2012-10-17 13:35:36 +00003987 // FIXME: Reactive when these tests can be more specific (not matching
3988 // implicit code on certain platforms), likely when we have hasDescendant for
3989 // Types/TypeLocs.
3990 //EXPECT_TRUE(matchAndVerifyResultTrue(
3991 // "int* a;",
3992 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3993 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3994 //EXPECT_TRUE(matchAndVerifyResultTrue(
3995 // "int* a;",
3996 // pointerTypeLoc().bind("loc"),
3997 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasperce620072012-10-17 08:52:59 +00003998 EXPECT_TRUE(matches(
3999 "int** a;",
David Blaikie5be093c2013-02-18 19:04:16 +00004000 loc(pointerType(pointee(qualType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00004001 EXPECT_TRUE(matches(
4002 "int** a;",
4003 loc(pointerType(pointee(pointerType())))));
4004 EXPECT_TRUE(matches(
4005 "int* b; int* * const a = &b;",
4006 loc(qualType(isConstQualified(), pointerType()))));
4007
4008 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper1802daf2012-10-17 13:35:36 +00004009 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4010 hasType(blockPointerType()))));
4011 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4012 hasType(memberPointerType()))));
4013 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4014 hasType(pointerType()))));
4015 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4016 hasType(referenceType()))));
Edwin Vanef4b48042013-03-07 15:44:40 +00004017 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4018 hasType(lValueReferenceType()))));
4019 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4020 hasType(rValueReferenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004021
Daniel Jasper1802daf2012-10-17 13:35:36 +00004022 Fragment = "int *ptr;";
4023 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4024 hasType(blockPointerType()))));
4025 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4026 hasType(memberPointerType()))));
4027 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4028 hasType(pointerType()))));
4029 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4030 hasType(referenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004031
Daniel Jasper1802daf2012-10-17 13:35:36 +00004032 Fragment = "int a; int &ref = a;";
4033 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4034 hasType(blockPointerType()))));
4035 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4036 hasType(memberPointerType()))));
4037 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4038 hasType(pointerType()))));
4039 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4040 hasType(referenceType()))));
Edwin Vanef4b48042013-03-07 15:44:40 +00004041 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4042 hasType(lValueReferenceType()))));
4043 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4044 hasType(rValueReferenceType()))));
4045
4046 Fragment = "int &&ref = 2;";
4047 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4048 hasType(blockPointerType()))));
4049 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4050 hasType(memberPointerType()))));
4051 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4052 hasType(pointerType()))));
4053 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4054 hasType(referenceType()))));
4055 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4056 hasType(lValueReferenceType()))));
4057 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4058 hasType(rValueReferenceType()))));
4059}
4060
4061TEST(TypeMatching, AutoRefTypes) {
4062 std::string Fragment = "auto a = 1;"
4063 "auto b = a;"
4064 "auto &c = a;"
4065 "auto &&d = c;"
4066 "auto &&e = 2;";
4067 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4068 hasType(referenceType()))));
4069 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4070 hasType(referenceType()))));
4071 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4072 hasType(referenceType()))));
4073 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4074 hasType(lValueReferenceType()))));
4075 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4076 hasType(rValueReferenceType()))));
4077 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4078 hasType(referenceType()))));
4079 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4080 hasType(lValueReferenceType()))));
4081 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4082 hasType(rValueReferenceType()))));
4083 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4084 hasType(referenceType()))));
4085 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4086 hasType(lValueReferenceType()))));
4087 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4088 hasType(rValueReferenceType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004089}
4090
4091TEST(TypeMatching, PointeeTypes) {
4092 EXPECT_TRUE(matches("int b; int &a = b;",
4093 referenceType(pointee(builtinType()))));
4094 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4095
4096 EXPECT_TRUE(matches("int *a;",
David Blaikie5be093c2013-02-18 19:04:16 +00004097 loc(pointerType(pointee(builtinType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00004098
4099 EXPECT_TRUE(matches(
4100 "int const *A;",
4101 pointerType(pointee(isConstQualified(), builtinType()))));
4102 EXPECT_TRUE(notMatches(
4103 "int *A;",
4104 pointerType(pointee(isConstQualified(), builtinType()))));
4105}
4106
4107TEST(TypeMatching, MatchesPointersToConstTypes) {
4108 EXPECT_TRUE(matches("int b; int * const a = &b;",
4109 loc(pointerType())));
4110 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikie5be093c2013-02-18 19:04:16 +00004111 loc(pointerType())));
Daniel Jasperce620072012-10-17 08:52:59 +00004112 EXPECT_TRUE(matches(
4113 "int b; const int * a = &b;",
David Blaikie5be093c2013-02-18 19:04:16 +00004114 loc(pointerType(pointee(builtinType())))));
Daniel Jasperce620072012-10-17 08:52:59 +00004115 EXPECT_TRUE(matches(
4116 "int b; const int * a = &b;",
4117 pointerType(pointee(builtinType()))));
4118}
4119
4120TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper1802daf2012-10-17 13:35:36 +00004121 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4122 hasType(typedefType()))));
Daniel Jasperce620072012-10-17 08:52:59 +00004123}
4124
Edwin Vane3abf7782013-02-25 14:49:29 +00004125TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vane742d9e72013-02-25 20:43:32 +00004126 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vane3abf7782013-02-25 14:49:29 +00004127 templateSpecializationType()));
4128}
4129
Edwin Vane742d9e72013-02-25 20:43:32 +00004130TEST(TypeMatching, MatchesRecordType) {
4131 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek0cc798f2013-02-27 11:56:58 +00004132 EXPECT_TRUE(matches("struct S{}; S s;",
4133 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4134 EXPECT_TRUE(notMatches("int i;",
4135 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vane742d9e72013-02-25 20:43:32 +00004136}
4137
4138TEST(TypeMatching, MatchesElaboratedType) {
4139 EXPECT_TRUE(matches(
4140 "namespace N {"
4141 " namespace M {"
4142 " class D {};"
4143 " }"
4144 "}"
4145 "N::M::D d;", elaboratedType()));
4146 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4147 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4148}
4149
4150TEST(ElaboratedTypeNarrowing, hasQualifier) {
4151 EXPECT_TRUE(matches(
4152 "namespace N {"
4153 " namespace M {"
4154 " class D {};"
4155 " }"
4156 "}"
4157 "N::M::D d;",
4158 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4159 EXPECT_TRUE(notMatches(
4160 "namespace M {"
4161 " class D {};"
4162 "}"
4163 "M::D d;",
4164 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vaneaec89ac2013-03-04 17:51:00 +00004165 EXPECT_TRUE(notMatches(
4166 "struct D {"
4167 "} d;",
4168 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vane742d9e72013-02-25 20:43:32 +00004169}
4170
4171TEST(ElaboratedTypeNarrowing, namesType) {
4172 EXPECT_TRUE(matches(
4173 "namespace N {"
4174 " namespace M {"
4175 " class D {};"
4176 " }"
4177 "}"
4178 "N::M::D d;",
4179 elaboratedType(elaboratedType(namesType(recordType(
4180 hasDeclaration(namedDecl(hasName("D")))))))));
4181 EXPECT_TRUE(notMatches(
4182 "namespace M {"
4183 " class D {};"
4184 "}"
4185 "M::D d;",
4186 elaboratedType(elaboratedType(namesType(typedefType())))));
4187}
4188
Daniel Jaspera7564432012-09-13 13:11:25 +00004189TEST(NNS, MatchesNestedNameSpecifiers) {
4190 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4191 nestedNameSpecifier()));
4192 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4193 nestedNameSpecifier()));
4194 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4195 nestedNameSpecifier()));
4196
4197 EXPECT_TRUE(matches(
4198 "struct A { static void f() {} }; void g() { A::f(); }",
4199 nestedNameSpecifier()));
4200 EXPECT_TRUE(notMatches(
4201 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4202 nestedNameSpecifier()));
4203}
4204
Daniel Jasperb54b7642012-09-20 14:12:57 +00004205TEST(NullStatement, SimpleCases) {
4206 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4207 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4208}
4209
Daniel Jaspera7564432012-09-13 13:11:25 +00004210TEST(NNS, MatchesTypes) {
4211 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4212 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4213 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4214 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4215 Matcher));
4216 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4217}
4218
4219TEST(NNS, MatchesNamespaceDecls) {
4220 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4221 specifiesNamespace(hasName("ns")));
4222 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4223 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4224 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4225}
4226
4227TEST(NNS, BindsNestedNameSpecifiers) {
4228 EXPECT_TRUE(matchAndVerifyResultTrue(
4229 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4230 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4231 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4232}
4233
4234TEST(NNS, BindsNestedNameSpecifierLocs) {
4235 EXPECT_TRUE(matchAndVerifyResultTrue(
4236 "namespace ns { struct B {}; } ns::B b;",
4237 loc(nestedNameSpecifier()).bind("loc"),
4238 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4239}
4240
4241TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4242 EXPECT_TRUE(matches(
4243 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4244 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4245 EXPECT_TRUE(matches(
4246 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasperce620072012-10-17 08:52:59 +00004247 nestedNameSpecifierLoc(hasPrefix(
4248 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera7564432012-09-13 13:11:25 +00004249}
4250
Daniel Jasperd1ce3c12012-10-30 15:42:00 +00004251TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4252 std::string Fragment =
4253 "namespace a { struct A { struct B { struct C {}; }; }; };"
4254 "void f() { a::A::B::C c; }";
4255 EXPECT_TRUE(matches(
4256 Fragment,
4257 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4258 hasDescendant(nestedNameSpecifier(
4259 specifiesNamespace(hasName("a")))))));
4260 EXPECT_TRUE(notMatches(
4261 Fragment,
4262 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4263 has(nestedNameSpecifier(
4264 specifiesNamespace(hasName("a")))))));
4265 EXPECT_TRUE(matches(
4266 Fragment,
4267 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4268 has(nestedNameSpecifier(
4269 specifiesNamespace(hasName("a")))))));
4270
4271 // Not really useful because a NestedNameSpecifier can af at most one child,
4272 // but to complete the interface.
4273 EXPECT_TRUE(matchAndVerifyResultTrue(
4274 Fragment,
4275 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4276 forEach(nestedNameSpecifier().bind("x"))),
4277 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4278}
4279
4280TEST(NNS, NestedNameSpecifiersAsDescendants) {
4281 std::string Fragment =
4282 "namespace a { struct A { struct B { struct C {}; }; }; };"
4283 "void f() { a::A::B::C c; }";
4284 EXPECT_TRUE(matches(
4285 Fragment,
4286 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4287 asString("struct a::A")))))));
4288 EXPECT_TRUE(matchAndVerifyResultTrue(
4289 Fragment,
4290 functionDecl(hasName("f"),
4291 forEachDescendant(nestedNameSpecifier().bind("x"))),
4292 // Nested names: a, a::A and a::A::B.
4293 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4294}
4295
4296TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4297 std::string Fragment =
4298 "namespace a { struct A { struct B { struct C {}; }; }; };"
4299 "void f() { a::A::B::C c; }";
4300 EXPECT_TRUE(matches(
4301 Fragment,
4302 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4303 hasDescendant(loc(nestedNameSpecifier(
4304 specifiesNamespace(hasName("a"))))))));
4305 EXPECT_TRUE(notMatches(
4306 Fragment,
4307 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4308 has(loc(nestedNameSpecifier(
4309 specifiesNamespace(hasName("a"))))))));
4310 EXPECT_TRUE(matches(
4311 Fragment,
4312 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4313 has(loc(nestedNameSpecifier(
4314 specifiesNamespace(hasName("a"))))))));
4315
4316 EXPECT_TRUE(matchAndVerifyResultTrue(
4317 Fragment,
4318 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4319 forEach(nestedNameSpecifierLoc().bind("x"))),
4320 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4321}
4322
4323TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4324 std::string Fragment =
4325 "namespace a { struct A { struct B { struct C {}; }; }; };"
4326 "void f() { a::A::B::C c; }";
4327 EXPECT_TRUE(matches(
4328 Fragment,
4329 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4330 asString("struct a::A"))))))));
4331 EXPECT_TRUE(matchAndVerifyResultTrue(
4332 Fragment,
4333 functionDecl(hasName("f"),
4334 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4335 // Nested names: a, a::A and a::A::B.
4336 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4337}
4338
Manuel Klimek60969f52013-02-01 13:41:35 +00004339template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004340public:
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004341 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4342 StringRef InnerId)
4343 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jasper452abbc2012-10-29 10:48:25 +00004344 }
4345
Manuel Klimek60969f52013-02-01 13:41:35 +00004346 virtual bool run(const BoundNodes *Nodes) { return false; }
4347
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004348 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4349 const T *Node = Nodes->getNodeAs<T>(Id);
Stephen Hines176edba2014-12-01 14:53:08 -08004350 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4351 nullptr;
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004352 }
4353private:
4354 std::string Id;
4355 internal::Matcher<T> InnerMatcher;
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004356 std::string InnerId;
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004357};
4358
4359TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek60969f52013-02-01 13:41:35 +00004360 EXPECT_TRUE(matchAndVerifyResultTrue(
4361 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4362 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004363 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4364 "Y")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004365 EXPECT_TRUE(matchAndVerifyResultFalse(
4366 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4367 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004368 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4369 "Z")));
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004370}
4371
4372TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek60969f52013-02-01 13:41:35 +00004373 EXPECT_TRUE(matchAndVerifyResultTrue(
4374 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004375 new VerifyMatchOnNode<clang::Stmt>(
4376 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004377 EXPECT_TRUE(matchAndVerifyResultFalse(
4378 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004379 new VerifyMatchOnNode<clang::Stmt>(
4380 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004381}
4382
4383TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4384 EXPECT_TRUE(matchAndVerifyResultTrue(
4385 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4386 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004387 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek60969f52013-02-01 13:41:35 +00004388 EXPECT_TRUE(matchAndVerifyResultFalse(
4389 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4390 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimekcf87bff2013-02-06 10:33:21 +00004391 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimek3e2aa992012-10-24 14:47:44 +00004392}
4393
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004394template <typename T>
4395class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4396public:
4397 virtual bool run(const BoundNodes *Nodes) { return false; }
4398
4399 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4400 const T *Node = Nodes->getNodeAs<T>("");
4401 return verify(*Nodes, *Context, Node);
4402 }
4403
4404 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004405 // Use the original typed pointer to verify we can pass pointers to subtypes
4406 // to equalsNode.
4407 const T *TypedNode = cast<T>(Node);
Stephen Hines176edba2014-12-01 14:53:08 -08004408 return selectFirst<T>(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004409 "", match(stmt(hasParent(
4410 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004411 *Node, Context)) != nullptr;
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004412 }
4413 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004414 // Use the original typed pointer to verify we can pass pointers to subtypes
4415 // to equalsNode.
4416 const T *TypedNode = cast<T>(Node);
Stephen Hines176edba2014-12-01 14:53:08 -08004417 return selectFirst<T>(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004418 "", match(decl(hasParent(
4419 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004420 *Node, Context)) != nullptr;
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004421 }
4422};
4423
4424TEST(IsEqualTo, MatchesNodesByIdentity) {
4425 EXPECT_TRUE(matchAndVerifyResultTrue(
4426 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004427 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4428 EXPECT_TRUE(matchAndVerifyResultTrue(
4429 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4430 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekfa37c5c2013-02-07 12:42:10 +00004431}
4432
Stephen Hines176edba2014-12-01 14:53:08 -08004433TEST(MatchFinder, CheckProfiling) {
4434 MatchFinder::MatchFinderOptions Options;
4435 llvm::StringMap<llvm::TimeRecord> Records;
4436 Options.CheckProfiling.emplace(Records);
4437 MatchFinder Finder(std::move(Options));
4438
4439 struct NamedCallback : public MatchFinder::MatchCallback {
4440 void run(const MatchFinder::MatchResult &Result) override {}
4441 StringRef getID() const override { return "MyID"; }
4442 } Callback;
4443 Finder.addMatcher(decl(), &Callback);
4444 std::unique_ptr<FrontendActionFactory> Factory(
4445 newFrontendActionFactory(&Finder));
4446 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4447
4448 EXPECT_EQ(1u, Records.size());
4449 EXPECT_EQ("MyID", Records.begin()->getKey());
4450}
4451
Manuel Klimeke5793282012-11-02 01:31:03 +00004452class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4453public:
4454 VerifyStartOfTranslationUnit() : Called(false) {}
4455 virtual void run(const MatchFinder::MatchResult &Result) {
4456 EXPECT_TRUE(Called);
4457 }
4458 virtual void onStartOfTranslationUnit() {
4459 Called = true;
4460 }
4461 bool Called;
4462};
4463
4464TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4465 MatchFinder Finder;
4466 VerifyStartOfTranslationUnit VerifyCallback;
4467 Finder.addMatcher(decl(), &VerifyCallback);
Stephen Hines651f13c2014-04-23 16:59:28 -07004468 std::unique_ptr<FrontendActionFactory> Factory(
4469 newFrontendActionFactory(&Finder));
Manuel Klimeke5793282012-11-02 01:31:03 +00004470 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4471 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004472
4473 VerifyCallback.Called = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004474 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004475 ASSERT_TRUE(AST.get());
4476 Finder.matchAST(AST->getASTContext());
4477 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimeke5793282012-11-02 01:31:03 +00004478}
4479
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004480class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4481public:
4482 VerifyEndOfTranslationUnit() : Called(false) {}
4483 virtual void run(const MatchFinder::MatchResult &Result) {
4484 EXPECT_FALSE(Called);
4485 }
4486 virtual void onEndOfTranslationUnit() {
4487 Called = true;
4488 }
4489 bool Called;
4490};
4491
4492TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4493 MatchFinder Finder;
4494 VerifyEndOfTranslationUnit VerifyCallback;
4495 Finder.addMatcher(decl(), &VerifyCallback);
Stephen Hines651f13c2014-04-23 16:59:28 -07004496 std::unique_ptr<FrontendActionFactory> Factory(
4497 newFrontendActionFactory(&Finder));
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004498 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4499 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004500
4501 VerifyCallback.Called = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004502 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbourne51fcdf82013-11-07 22:30:36 +00004503 ASSERT_TRUE(AST.get());
4504 Finder.matchAST(AST->getASTContext());
4505 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne8f9e5902013-05-28 19:21:51 +00004506}
4507
Manuel Klimekcf52ca62013-06-20 14:06:32 +00004508TEST(EqualsBoundNodeMatcher, QualType) {
4509 EXPECT_TRUE(matches(
4510 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4511 hasInitializer(ignoringParenImpCasts(
4512 hasType(qualType(equalsBoundNode("type"))))))));
4513 EXPECT_TRUE(notMatches("int i = 1.f;",
4514 varDecl(hasType(qualType().bind("type")),
4515 hasInitializer(ignoringParenImpCasts(hasType(
4516 qualType(equalsBoundNode("type"))))))));
4517}
4518
4519TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4520 EXPECT_TRUE(notMatches(
4521 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4522 hasInitializer(ignoringParenImpCasts(
4523 hasType(qualType(equalsBoundNode("type"))))))));
4524}
4525
4526TEST(EqualsBoundNodeMatcher, Stmt) {
4527 EXPECT_TRUE(
4528 matches("void f() { if(true) {} }",
4529 stmt(allOf(ifStmt().bind("if"),
4530 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4531
4532 EXPECT_TRUE(notMatches(
4533 "void f() { if(true) { if (true) {} } }",
4534 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4535}
4536
4537TEST(EqualsBoundNodeMatcher, Decl) {
4538 EXPECT_TRUE(matches(
4539 "class X { class Y {}; };",
4540 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4541 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4542
4543 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4544 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4545 has(decl(equalsBoundNode("record")))))));
4546}
4547
4548TEST(EqualsBoundNodeMatcher, Type) {
4549 EXPECT_TRUE(matches(
4550 "class X { int a; int b; };",
4551 recordDecl(
4552 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4553 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4554
4555 EXPECT_TRUE(notMatches(
4556 "class X { int a; double b; };",
4557 recordDecl(
4558 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4559 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4560}
4561
4562TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekcf52ca62013-06-20 14:06:32 +00004563 EXPECT_TRUE(matchAndVerifyResultTrue(
4564 "int f() {"
4565 " if (1) {"
4566 " int i = 9;"
4567 " }"
4568 " int j = 10;"
4569 " {"
4570 " float k = 9.0;"
4571 " }"
4572 " return 0;"
4573 "}",
4574 // Look for variable declarations within functions whose type is the same
4575 // as the function return type.
4576 functionDecl(returns(qualType().bind("type")),
4577 forEachDescendant(varDecl(hasType(
4578 qualType(equalsBoundNode("type")))).bind("decl"))),
4579 // Only i and j should match, not k.
4580 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4581}
4582
4583TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4584 EXPECT_TRUE(matchAndVerifyResultTrue(
4585 "void f() {"
4586 " int x;"
4587 " double d;"
4588 " x = d + x - d + x;"
4589 "}",
4590 functionDecl(
4591 hasName("f"), forEachDescendant(varDecl().bind("d")),
4592 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4593 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4594}
4595
Stephen Hines651f13c2014-04-23 16:59:28 -07004596TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4597 EXPECT_TRUE(matchAndVerifyResultTrue(
4598 "struct StringRef { int size() const; const char* data() const; };"
4599 "void f(StringRef v) {"
4600 " v.data();"
4601 "}",
4602 memberCallExpr(
4603 callee(methodDecl(hasName("data"))),
4604 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4605 .bind("var")))),
4606 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4607 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4608 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4609 .bind("data"),
4610 new VerifyIdIsBoundTo<Expr>("data", 1)));
4611
4612 EXPECT_FALSE(matches(
4613 "struct StringRef { int size() const; const char* data() const; };"
4614 "void f(StringRef v) {"
4615 " v.data();"
4616 " v.size();"
4617 "}",
4618 memberCallExpr(
4619 callee(methodDecl(hasName("data"))),
4620 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4621 .bind("var")))),
4622 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4623 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4624 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4625 .bind("data")));
4626}
4627
Manuel Klimek4da21662012-07-06 05:48:52 +00004628} // end namespace ast_matchers
4629} // end namespace clang