blob: f5cb130b1d7344ead670d6c76baf56a96a2baff4 [file] [log] [blame]
Manuel Klimek04616e42012-07-06 05:48:52 +00001//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher unit tests ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ASTMatchersTest.h"
Benjamin Kramere5015e52012-12-01 17:22:05 +000011#include "clang/AST/PrettyPrinter.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Chandler Carruth320d9662012-12-04 09:45:34 +000013#include "clang/ASTMatchers/ASTMatchers.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000014#include "clang/Tooling/Tooling.h"
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +000015#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000017#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000022#if GTEST_HAS_DEATH_TEST
Manuel Klimek04616e42012-07-06 05:48:52 +000023TEST(HasNameDeathTest, DiesOnEmptyName) {
24 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000025 DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000026 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27 }, "");
28}
29
Daniel Jasper1dad1832012-07-10 20:20:19 +000030TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000032 DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
Daniel Jasper1dad1832012-07-10 20:20:19 +000033 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34 }, "");
35}
36
Manuel Klimek04616e42012-07-06 05:48:52 +000037TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000039 DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000040 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41 }, "");
42}
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000043#endif
Manuel Klimek04616e42012-07-06 05:48:52 +000044
Peter Collingbourne2b9471302013-11-07 22:30:32 +000045TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46 MatchFinder Finder;
Craig Topper416fa342014-06-08 08:38:12 +000047 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50 nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000051
52 // Do not accept non-toplevel matchers.
Craig Topper416fa342014-06-08 08:38:12 +000053 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54 EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000056}
57
Manuel Klimeke9235692012-07-25 10:02:02 +000058TEST(Decl, MatchesDeclarations) {
59 EXPECT_TRUE(notMatches("", decl(usingDecl())));
60 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
61 decl(usingDecl())));
62}
63
Manuel Klimek04616e42012-07-06 05:48:52 +000064TEST(NameableDeclaration, MatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000065 DeclarationMatcher NamedX = namedDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +000066 EXPECT_TRUE(matches("typedef int X;", NamedX));
67 EXPECT_TRUE(matches("int X;", NamedX));
68 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
69 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
70 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
71 EXPECT_TRUE(matches("namespace X { }", NamedX));
Daniel Jasper1dad1832012-07-10 20:20:19 +000072 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
Manuel Klimek04616e42012-07-06 05:48:52 +000073
74 EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
Daniel Jasper1dad1832012-07-10 20:20:19 +000077TEST(NameableDeclaration, REMatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000078 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000079 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
80 EXPECT_TRUE(matches("int Xb;", NamedX));
81 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
82 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
83 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
84 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
85 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
86
87 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
88
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000089 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000090 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
91 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
92
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000093 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000094 EXPECT_TRUE(matches("int abc;", Abc));
95 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
96 EXPECT_TRUE(notMatches("int cab;", Abc));
97 EXPECT_TRUE(matches("int cabc;", Abc));
Manuel Klimeke792efd2012-12-10 07:08:53 +000098
99 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
100 EXPECT_TRUE(matches("int k;", StartsWithK));
101 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
102 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
103 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
104 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000105}
106
Manuel Klimek04616e42012-07-06 05:48:52 +0000107TEST(DeclarationMatcher, MatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000108 DeclarationMatcher ClassMatcher(recordDecl());
Saleem Abdulrasool377066a2014-03-27 22:50:18 +0000109 llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110 if (Triple.getOS() != llvm::Triple::Win32 ||
111 Triple.getEnvironment() != llvm::Triple::MSVC)
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +0000112 EXPECT_FALSE(matches("", ClassMatcher));
113 else
114 // Matches class type_info.
115 EXPECT_TRUE(matches("", ClassMatcher));
Manuel Klimek04616e42012-07-06 05:48:52 +0000116
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000117 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000118 EXPECT_TRUE(matches("class X;", ClassX));
119 EXPECT_TRUE(matches("class X {};", ClassX));
120 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
121 EXPECT_TRUE(notMatches("", ClassX));
122}
123
124TEST(DeclarationMatcher, ClassIsDerived) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000125 DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000126
127 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000128 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
Manuel Klimek04616e42012-07-06 05:48:52 +0000130 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131 EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
Daniel Jasperd6b82cb2012-09-12 21:14:15 +0000133 DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000134
135 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
136 EXPECT_TRUE(matches("class X {};", IsAX));
137 EXPECT_TRUE(matches("class X;", IsAX));
138 EXPECT_TRUE(notMatches("class Y;", IsAX));
139 EXPECT_TRUE(notMatches("", IsAX));
140
Manuel Klimek04616e42012-07-06 05:48:52 +0000141 DeclarationMatcher ZIsDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000142 recordDecl(hasName("Z"), isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000143 EXPECT_TRUE(
144 matches("class X {}; class Y : public X {}; class Z : public Y {};",
145 ZIsDerivedFromX));
146 EXPECT_TRUE(
147 matches("class X {};"
148 "template<class T> class Y : public X {};"
149 "class Z : public Y<int> {};", ZIsDerivedFromX));
150 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
151 ZIsDerivedFromX));
152 EXPECT_TRUE(
153 matches("template<class T> class X {}; "
154 "template<class T> class Z : public X<T> {};",
155 ZIsDerivedFromX));
156 EXPECT_TRUE(
157 matches("template<class T, class U=T> class X {}; "
158 "template<class T> class Z : public X<T> {};",
159 ZIsDerivedFromX));
160 EXPECT_TRUE(
161 notMatches("template<class X> class A { class Z : public X {}; };",
162 ZIsDerivedFromX));
163 EXPECT_TRUE(
164 matches("template<class X> class A { public: class Z : public X {}; }; "
165 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
166 EXPECT_TRUE(
167 matches("template <class T> class X {}; "
168 "template<class Y> class A { class Z : public X<Y> {}; };",
169 ZIsDerivedFromX));
170 EXPECT_TRUE(
171 notMatches("template<template<class T> class X> class A { "
172 " class Z : public X<int> {}; };", ZIsDerivedFromX));
173 EXPECT_TRUE(
174 matches("template<template<class T> class X> class A { "
175 " public: class Z : public X<int> {}; }; "
176 "template<class T> class X {}; void y() { A<X>::Z z; }",
177 ZIsDerivedFromX));
178 EXPECT_TRUE(
179 notMatches("template<class X> class A { class Z : public X::D {}; };",
180 ZIsDerivedFromX));
181 EXPECT_TRUE(
182 matches("template<class X> class A { public: "
183 " class Z : public X::D {}; }; "
184 "class Y { public: class X {}; typedef X D; }; "
185 "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
186 EXPECT_TRUE(
187 matches("class X {}; typedef X Y; class Z : public Y {};",
188 ZIsDerivedFromX));
189 EXPECT_TRUE(
190 matches("template<class T> class Y { typedef typename T::U X; "
191 " class Z : public X {}; };", ZIsDerivedFromX));
192 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
193 ZIsDerivedFromX));
194 EXPECT_TRUE(
195 notMatches("template<class T> class X {}; "
196 "template<class T> class A { class Z : public X<T>::D {}; };",
197 ZIsDerivedFromX));
198 EXPECT_TRUE(
199 matches("template<class T> class X { public: typedef X<T> D; }; "
200 "template<class T> class A { public: "
201 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
202 ZIsDerivedFromX));
203 EXPECT_TRUE(
204 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
205 ZIsDerivedFromX));
206 EXPECT_TRUE(
207 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
208 ZIsDerivedFromX));
209 EXPECT_TRUE(
210 matches("class X {}; class Y : public X {}; "
211 "typedef Y V; typedef V W; class Z : public W {};",
212 ZIsDerivedFromX));
213 EXPECT_TRUE(
214 matches("template<class T, class U> class X {}; "
215 "template<class T> class A { class Z : public X<T, int> {}; };",
216 ZIsDerivedFromX));
217 EXPECT_TRUE(
218 notMatches("template<class X> class D { typedef X A; typedef A B; "
219 " typedef B C; class Z : public C {}; };",
220 ZIsDerivedFromX));
221 EXPECT_TRUE(
222 matches("class X {}; typedef X A; typedef A B; "
223 "class Z : public B {};", ZIsDerivedFromX));
224 EXPECT_TRUE(
225 matches("class X {}; typedef X A; typedef A B; typedef B C; "
226 "class Z : public C {};", ZIsDerivedFromX));
227 EXPECT_TRUE(
228 matches("class U {}; typedef U X; typedef X V; "
229 "class Z : public V {};", ZIsDerivedFromX));
230 EXPECT_TRUE(
231 matches("class Base {}; typedef Base X; "
232 "class Z : public Base {};", ZIsDerivedFromX));
233 EXPECT_TRUE(
234 matches("class Base {}; typedef Base Base2; typedef Base2 X; "
235 "class Z : public Base {};", ZIsDerivedFromX));
236 EXPECT_TRUE(
237 notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
238 "class Z : public Base {};", ZIsDerivedFromX));
239 EXPECT_TRUE(
240 matches("class A {}; typedef A X; typedef A Y; "
241 "class Z : public Y {};", ZIsDerivedFromX));
242 EXPECT_TRUE(
243 notMatches("template <typename T> class Z;"
244 "template <> class Z<void> {};"
245 "template <typename T> class Z : public Z<void> {};",
246 IsDerivedFromX));
247 EXPECT_TRUE(
248 matches("template <typename T> class X;"
249 "template <> class X<void> {};"
250 "template <typename T> class X : public X<void> {};",
251 IsDerivedFromX));
252 EXPECT_TRUE(matches(
253 "class X {};"
254 "template <typename T> class Z;"
255 "template <> class Z<void> {};"
256 "template <typename T> class Z : public Z<void>, public X {};",
257 ZIsDerivedFromX));
Manuel Klimek5472a522012-12-04 13:40:29 +0000258 EXPECT_TRUE(
259 notMatches("template<int> struct X;"
260 "template<int i> struct X : public X<i-1> {};",
261 recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
262 EXPECT_TRUE(matches(
263 "struct A {};"
264 "template<int> struct X;"
265 "template<int i> struct X : public X<i-1> {};"
266 "template<> struct X<0> : public A {};"
267 "struct B : public X<42> {};",
268 recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000269
270 // FIXME: Once we have better matchers for template type matching,
271 // get rid of the Variable(...) matching and match the right template
272 // declarations directly.
273 const char *RecursiveTemplateOneParameter =
274 "class Base1 {}; class Base2 {};"
275 "template <typename T> class Z;"
276 "template <> class Z<void> : public Base1 {};"
277 "template <> class Z<int> : public Base2 {};"
278 "template <> class Z<float> : public Z<void> {};"
279 "template <> class Z<double> : public Z<int> {};"
280 "template <typename T> class Z : public Z<float>, public Z<double> {};"
281 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
282 EXPECT_TRUE(matches(
283 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000284 varDecl(hasName("z_float"),
285 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000286 EXPECT_TRUE(notMatches(
287 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000288 varDecl(hasName("z_float"),
289 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000290 EXPECT_TRUE(matches(
291 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000292 varDecl(hasName("z_char"),
293 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
294 isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000295
296 const char *RecursiveTemplateTwoParameters =
297 "class Base1 {}; class Base2 {};"
298 "template <typename T1, typename T2> class Z;"
299 "template <typename T> class Z<void, T> : public Base1 {};"
300 "template <typename T> class Z<int, T> : public Base2 {};"
301 "template <typename T> class Z<float, T> : public Z<void, T> {};"
302 "template <typename T> class Z<double, T> : public Z<int, T> {};"
303 "template <typename T1, typename T2> class Z : "
304 " public Z<float, T2>, public Z<double, T2> {};"
305 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
306 " Z<char, void> z_char; }";
307 EXPECT_TRUE(matches(
308 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000309 varDecl(hasName("z_float"),
310 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000311 EXPECT_TRUE(notMatches(
312 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000313 varDecl(hasName("z_float"),
314 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000315 EXPECT_TRUE(matches(
316 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000317 varDecl(hasName("z_char"),
318 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
319 isDerivedFrom("Base2")))))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000322 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000325 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000329 recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
Manuel Klimek1863e502013-08-02 21:24:09 +0000330
331 EXPECT_TRUE(matches(
332 "template<typename T> class X {};"
333 "template<typename T> using Z = X<T>;"
334 "template <typename T> class Y : Z<T> {};",
335 recordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000336}
337
Edwin Vane0a4836e2013-03-06 17:02:57 +0000338TEST(DeclarationMatcher, hasMethod) {
339 EXPECT_TRUE(matches("class A { void func(); };",
340 recordDecl(hasMethod(hasName("func")))));
341 EXPECT_TRUE(notMatches("class A { void func(); };",
342 recordDecl(hasMethod(isPublic()))));
343}
344
Daniel Jasper83dafaf2012-09-18 14:17:42 +0000345TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
346 EXPECT_TRUE(matches(
347 "template <typename T> struct A {"
348 " template <typename T2> struct F {};"
349 "};"
350 "template <typename T> struct B : A<T>::template F<T> {};"
351 "B<int> b;",
352 recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
353}
354
Edwin Vaneb6eae142013-02-25 20:43:32 +0000355TEST(DeclarationMatcher, hasDeclContext) {
356 EXPECT_TRUE(matches(
357 "namespace N {"
358 " namespace M {"
359 " class D {};"
360 " }"
361 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000362 recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000363 EXPECT_TRUE(notMatches(
364 "namespace N {"
365 " namespace M {"
366 " class D {};"
367 " }"
368 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000369 recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
370
371 EXPECT_TRUE(matches("namespace {"
372 " namespace M {"
373 " class D {};"
374 " }"
375 "}",
376 recordDecl(hasDeclContext(namespaceDecl(
377 hasName("M"), hasDeclContext(namespaceDecl()))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000378}
379
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000380TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000381 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000382 EXPECT_TRUE(notMatches("class X;", ClassX));
383 EXPECT_TRUE(notMatches("class X {};", ClassX));
384}
385
386TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000387 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000388 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
389 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
390}
391
392TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
393 EXPECT_TRUE(notMatches("template<typename T> class X { };"
394 "template<> class X<int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000395 classTemplateDecl(hasName("X"),
396 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000397}
398
399TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
400 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
401 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000402 classTemplateDecl(hasName("X"),
403 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000404}
405
Daniel Jasper4e566c42012-07-12 08:50:38 +0000406TEST(AllOf, AllOverloadsWork) {
407 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000408 "struct T { };"
409 "int f(int, T*, int, int);"
410 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000411 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000412 callExpr(allOf(callee(functionDecl(hasName("f"))),
413 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000414 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000415 callExpr(allOf(callee(functionDecl(hasName("f"))),
416 hasArgument(0, declRefExpr(to(varDecl()))),
417 hasArgument(1, hasType(pointsTo(
418 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000419 EXPECT_TRUE(matches(Program,
420 callExpr(allOf(callee(functionDecl(hasName("f"))),
421 hasArgument(0, declRefExpr(to(varDecl()))),
422 hasArgument(1, hasType(pointsTo(
423 recordDecl(hasName("T"))))),
424 hasArgument(2, integerLiteral(equals(3)))))));
425 EXPECT_TRUE(matches(Program,
426 callExpr(allOf(callee(functionDecl(hasName("f"))),
427 hasArgument(0, declRefExpr(to(varDecl()))),
428 hasArgument(1, hasType(pointsTo(
429 recordDecl(hasName("T"))))),
430 hasArgument(2, integerLiteral(equals(3))),
431 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000432}
433
Manuel Klimek04616e42012-07-06 05:48:52 +0000434TEST(DeclarationMatcher, MatchAnyOf) {
435 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000436 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000437 EXPECT_TRUE(
438 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
439 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
440 EXPECT_TRUE(
441 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
442 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
443
Daniel Jasper84c763e2012-07-15 19:57:12 +0000444 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000445 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000446 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
447 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
448
Manuel Klimek04616e42012-07-06 05:48:52 +0000449 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000450 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
451 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000452 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
453 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
454 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
455 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
456 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
457 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
458}
459
460TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000461 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000462 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
463 EXPECT_TRUE(matches("class X {};", HasClassX));
464
465 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000466 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000467 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
468 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
469 EXPECT_TRUE(
470 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
471}
472
473TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
474 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000475 recordDecl(
476 has(recordDecl(
477 has(recordDecl(hasName("X"))),
478 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000479 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000480 has(recordDecl(
481 has(recordDecl(hasName("A"))),
482 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000483 hasName("C"))),
484 hasName("F"));
485
486 EXPECT_TRUE(matches(
487 "class F {"
488 " class Z {"
489 " class X {};"
490 " class Y {};"
491 " };"
492 " class C {"
493 " class A {};"
494 " class B {};"
495 " };"
496 "};", Recursive));
497
498 EXPECT_TRUE(matches(
499 "class F {"
500 " class Z {"
501 " class A {};"
502 " class X {};"
503 " class Y {};"
504 " };"
505 " class C {"
506 " class X {};"
507 " class A {};"
508 " class B {};"
509 " };"
510 "};", Recursive));
511
512 EXPECT_TRUE(matches(
513 "class O1 {"
514 " class O2 {"
515 " class F {"
516 " class Z {"
517 " class A {};"
518 " class X {};"
519 " class Y {};"
520 " };"
521 " class C {"
522 " class X {};"
523 " class A {};"
524 " class B {};"
525 " };"
526 " };"
527 " };"
528 "};", Recursive));
529}
530
531TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
532 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000533 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000534 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000535 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000536 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000537 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000538 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000539 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000540 hasName("Y"))),
541 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000542 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000543 anyOf(
544 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000545 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000546 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000547 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000548 hasName("B")))))),
549 hasName("F")));
550
551 EXPECT_TRUE(matches("class F {};", Recursive));
552 EXPECT_TRUE(matches("class Z {};", Recursive));
553 EXPECT_TRUE(matches("class C {};", Recursive));
554 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
555 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
556 EXPECT_TRUE(
557 matches("class O1 { class O2 {"
558 " class M { class N { class B {}; }; }; "
559 "}; };", Recursive));
560}
561
562TEST(DeclarationMatcher, MatchNot) {
563 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000564 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000565 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000566 unless(hasName("X")));
567 EXPECT_TRUE(notMatches("", NotClassX));
568 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
569 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
570 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
571 EXPECT_TRUE(
572 notMatches("class Y {}; class Z {}; class X : public Y {};",
573 NotClassX));
574
575 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000576 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000577 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000578 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000579 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000580 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000581 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
582 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
583 ClassXHasNotClassY));
584}
585
586TEST(DeclarationMatcher, HasDescendant) {
587 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000588 recordDecl(
589 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000590 hasName("Z"));
591 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
592 EXPECT_TRUE(
593 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
594 EXPECT_TRUE(
595 matches("class Z { class A { class Y { class X {}; }; }; };",
596 ZDescendantClassX));
597 EXPECT_TRUE(
598 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
599 ZDescendantClassX));
600 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
601
602 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000603 recordDecl(
604 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000605 hasName("X"))),
606 hasName("Z"));
607 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
608 ZDescendantClassXHasClassY));
609 EXPECT_TRUE(
610 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
611 ZDescendantClassXHasClassY));
612 EXPECT_TRUE(notMatches(
613 "class Z {"
614 " class A {"
615 " class B {"
616 " class X {"
617 " class C {"
618 " class Y {};"
619 " };"
620 " };"
621 " }; "
622 " };"
623 "};", ZDescendantClassXHasClassY));
624
625 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000626 recordDecl(
627 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
628 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000629 hasName("Z"));
630 EXPECT_TRUE(
631 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
632 ZDescendantClassXDescendantClassY));
633 EXPECT_TRUE(matches(
634 "class Z {"
635 " class A {"
636 " class X {"
637 " class B {"
638 " class Y {};"
639 " };"
640 " class Y {};"
641 " };"
642 " };"
643 "};", ZDescendantClassXDescendantClassY));
644}
645
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000646// Implements a run method that returns whether BoundNodes contains a
647// Decl bound to Id that can be dynamically cast to T.
648// Optionally checks that the check succeeded a specific number of times.
649template <typename T>
650class VerifyIdIsBoundTo : public BoundNodesCallback {
651public:
652 // Create an object that checks that a node of type \c T was bound to \c Id.
653 // Does not check for a certain number of matches.
654 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
655 : Id(Id), ExpectedCount(-1), Count(0) {}
656
657 // Create an object that checks that a node of type \c T was bound to \c Id.
658 // Checks that there were exactly \c ExpectedCount matches.
659 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
660 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
661
662 // Create an object that checks that a node of type \c T was bound to \c Id.
663 // Checks that there was exactly one match with the name \c ExpectedName.
664 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000665 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
666 int ExpectedCount = 1)
667 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
668 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000669
Craig Toppera798a9d2014-03-02 09:32:10 +0000670 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000671 if (ExpectedCount != -1)
672 EXPECT_EQ(ExpectedCount, Count);
673 if (!ExpectedName.empty())
674 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000675 Count = 0;
676 Name.clear();
677 }
678
679 ~VerifyIdIsBoundTo() {
680 EXPECT_EQ(0, Count);
681 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000682 }
683
684 virtual bool run(const BoundNodes *Nodes) {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000685 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000686 if (Nodes->getNodeAs<T>(Id)) {
687 ++Count;
688 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
689 Name = Named->getNameAsString();
690 } else if (const NestedNameSpecifier *NNS =
691 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
692 llvm::raw_string_ostream OS(Name);
693 NNS->print(OS, PrintingPolicy(LangOptions()));
694 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000695 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
696 EXPECT_NE(M.end(), I);
697 if (I != M.end())
698 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000699 return true;
700 }
Craig Topper416fa342014-06-08 08:38:12 +0000701 EXPECT_TRUE(M.count(Id) == 0 ||
702 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000703 return false;
704 }
705
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000706 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
707 return run(Nodes);
708 }
709
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000710private:
711 const std::string Id;
712 const int ExpectedCount;
713 int Count;
714 const std::string ExpectedName;
715 std::string Name;
716};
717
718TEST(HasDescendant, MatchesDescendantTypes) {
719 EXPECT_TRUE(matches("void f() { int i = 3; }",
720 decl(hasDescendant(loc(builtinType())))));
721 EXPECT_TRUE(matches("void f() { int i = 3; }",
722 stmt(hasDescendant(builtinType()))));
723
724 EXPECT_TRUE(matches("void f() { int i = 3; }",
725 stmt(hasDescendant(loc(builtinType())))));
726 EXPECT_TRUE(matches("void f() { int i = 3; }",
727 stmt(hasDescendant(qualType(builtinType())))));
728
729 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
730 stmt(hasDescendant(isInteger()))));
731
732 EXPECT_TRUE(matchAndVerifyResultTrue(
733 "void f() { int a; float c; int d; int e; }",
734 functionDecl(forEachDescendant(
735 varDecl(hasDescendant(isInteger())).bind("x"))),
736 new VerifyIdIsBoundTo<Decl>("x", 3)));
737}
738
739TEST(HasDescendant, MatchesDescendantsOfTypes) {
740 EXPECT_TRUE(matches("void f() { int*** i; }",
741 qualType(hasDescendant(builtinType()))));
742 EXPECT_TRUE(matches("void f() { int*** i; }",
743 qualType(hasDescendant(
744 pointerType(pointee(builtinType()))))));
745 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000746 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000747
748 EXPECT_TRUE(matchAndVerifyResultTrue(
749 "void f() { int*** i; }",
750 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
751 new VerifyIdIsBoundTo<Type>("x", 2)));
752}
753
754TEST(Has, MatchesChildrenOfTypes) {
755 EXPECT_TRUE(matches("int i;",
756 varDecl(hasName("i"), has(isInteger()))));
757 EXPECT_TRUE(notMatches("int** i;",
758 varDecl(hasName("i"), has(isInteger()))));
759 EXPECT_TRUE(matchAndVerifyResultTrue(
760 "int (*f)(float, int);",
761 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
762 new VerifyIdIsBoundTo<QualType>("x", 2)));
763}
764
765TEST(Has, MatchesChildTypes) {
766 EXPECT_TRUE(matches(
767 "int* i;",
768 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
769 EXPECT_TRUE(notMatches(
770 "int* i;",
771 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
772}
773
Daniel Jasper1dad1832012-07-10 20:20:19 +0000774TEST(Enum, DoesNotMatchClasses) {
775 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
776}
777
778TEST(Enum, MatchesEnums) {
779 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
780}
781
782TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000783 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000784 EXPECT_TRUE(matches("enum X{ A };", Matcher));
785 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
786 EXPECT_TRUE(notMatches("enum X {};", Matcher));
787}
788
Manuel Klimek04616e42012-07-06 05:48:52 +0000789TEST(StatementMatcher, Has) {
790 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000791 expr(hasType(pointsTo(recordDecl(hasName("X")))),
792 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000793
794 EXPECT_TRUE(matches(
795 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
796 EXPECT_TRUE(notMatches(
797 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
798}
799
800TEST(StatementMatcher, HasDescendant) {
801 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000802 expr(hasType(pointsTo(recordDecl(hasName("X")))),
803 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000804
805 EXPECT_TRUE(matches(
806 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
807 HasDescendantVariableI));
808 EXPECT_TRUE(notMatches(
809 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
810 HasDescendantVariableI));
811}
812
813TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000814 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000815
816 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
817 EXPECT_TRUE(notMatches("class A {};", TypeA));
818
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000819 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000820
821 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
822 TypeDerivedFromA));
823 EXPECT_TRUE(notMatches("class A {};", TypeA));
824
825 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000826 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000827
828 EXPECT_TRUE(
829 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
830}
831
Manuel Klimek04616e42012-07-06 05:48:52 +0000832TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000833 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000834
835 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000836 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000837
838 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000839 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000840
841 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000842 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000843
844 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
845 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000846 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000847
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000848 StatementMatcher MethodX =
849 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000850
851 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
852 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000853 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000854}
855
856TEST(Matcher, BindTheSameNameInAlternatives) {
857 StatementMatcher matcher = anyOf(
858 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000859 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000860 hasRHS(integerLiteral(equals(0)))),
861 binaryOperator(hasOperatorName("+"),
862 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000863 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000864
865 EXPECT_TRUE(matchAndVerifyResultTrue(
866 // The first branch of the matcher binds x to 0 but then fails.
867 // The second branch binds x to f() and succeeds.
868 "int f() { return 0 + f(); }",
869 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000870 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000871}
872
Manuel Klimekfdf98762012-08-30 19:41:06 +0000873TEST(Matcher, BindsIDForMemoizedResults) {
874 // Using the same matcher in two match expressions will make memoization
875 // kick in.
876 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
877 EXPECT_TRUE(matchAndVerifyResultTrue(
878 "class A { class B { class X {}; }; };",
879 DeclarationMatcher(anyOf(
880 recordDecl(hasName("A"), hasDescendant(ClassX)),
881 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000882 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000883}
884
Daniel Jasper856194d02012-12-03 15:43:25 +0000885TEST(HasDeclaration, HasDeclarationOfEnumType) {
886 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
887 expr(hasType(pointsTo(
888 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
889}
890
Edwin Vaneed936452013-02-25 14:32:42 +0000891TEST(HasDeclaration, HasGetDeclTraitTest) {
892 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
893 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
894 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
895}
896
Edwin Vane2c197e02013-02-19 17:14:34 +0000897TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
898 EXPECT_TRUE(matches("typedef int X; X a;",
899 varDecl(hasName("a"),
900 hasType(typedefType(hasDeclaration(decl()))))));
901
902 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
903}
904
Edwin Vanef901b712013-02-25 14:49:29 +0000905TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
906 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
907 varDecl(hasType(templateSpecializationType(
908 hasDeclaration(namedDecl(hasName("A"))))))));
909}
910
Manuel Klimek04616e42012-07-06 05:48:52 +0000911TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000912 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000913 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000914 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000915 EXPECT_TRUE(
916 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000917 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000918 EXPECT_TRUE(
919 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000920 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000921}
922
923TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000924 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000925 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000926 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000927 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000928 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000929 EXPECT_TRUE(
930 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000931 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000932}
933
934TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000935 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000936 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000937 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000938 EXPECT_TRUE(
939 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000940 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000941}
942
943TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000944 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000945 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000946 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000947 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000948 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000949}
950
Manuel Klimekc16c6522013-06-20 13:08:29 +0000951TEST(HasTypeLoc, MatchesDeclaratorDecls) {
952 EXPECT_TRUE(matches("int x;",
953 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
954
955 // Make sure we don't crash on implicit constructors.
956 EXPECT_TRUE(notMatches("class X {}; X x;",
957 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
958}
959
Manuel Klimek04616e42012-07-06 05:48:52 +0000960TEST(Matcher, Call) {
961 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +0000962 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000963 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000964
965 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
966 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
967
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000968 StatementMatcher MethodOnY =
969 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000970
971 EXPECT_TRUE(
972 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
973 MethodOnY));
974 EXPECT_TRUE(
975 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
976 MethodOnY));
977 EXPECT_TRUE(
978 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
979 MethodOnY));
980 EXPECT_TRUE(
981 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
982 MethodOnY));
983 EXPECT_TRUE(
984 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
985 MethodOnY));
986
987 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000988 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000989
990 EXPECT_TRUE(
991 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
992 MethodOnYPointer));
993 EXPECT_TRUE(
994 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
995 MethodOnYPointer));
996 EXPECT_TRUE(
997 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
998 MethodOnYPointer));
999 EXPECT_TRUE(
1000 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1001 MethodOnYPointer));
1002 EXPECT_TRUE(
1003 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1004 MethodOnYPointer));
1005}
1006
Daniel Jasper5901e472012-10-01 13:40:41 +00001007TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001008 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001009 lambdaExpr()));
1010}
1011
1012TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001013 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1014 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001015 forRangeStmt()));
1016 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1017 forRangeStmt()));
1018}
1019
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001020TEST(Matcher, SubstNonTypeTemplateParm) {
1021 EXPECT_FALSE(matches("template<int N>\n"
1022 "struct A { static const int n = 0; };\n"
1023 "struct B : public A<42> {};",
1024 substNonTypeTemplateParmExpr()));
1025 EXPECT_TRUE(matches("template<int N>\n"
1026 "struct A { static const int n = N; };\n"
1027 "struct B : public A<42> {};",
1028 substNonTypeTemplateParmExpr()));
1029}
1030
Daniel Jasper5901e472012-10-01 13:40:41 +00001031TEST(Matcher, UserDefinedLiteral) {
1032 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1033 " return i + 1;"
1034 "}"
1035 "char c = 'a'_inc;",
1036 userDefinedLiteral()));
1037}
1038
Daniel Jasper87c3d362012-09-20 14:12:57 +00001039TEST(Matcher, FlowControl) {
1040 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1041 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1042 continueStmt()));
1043 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1044 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1045 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1046}
1047
Daniel Jasper1dad1832012-07-10 20:20:19 +00001048TEST(HasType, MatchesAsString) {
1049 EXPECT_TRUE(
1050 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001051 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001052 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001053 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001054 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001055 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001056 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001057 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001058}
1059
Manuel Klimek04616e42012-07-06 05:48:52 +00001060TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001061 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001062 // Unary operator
1063 EXPECT_TRUE(matches("class Y { }; "
1064 "bool operator!(Y x) { return false; }; "
1065 "Y y; bool c = !y;", OpCall));
1066 // No match -- special operators like "new", "delete"
1067 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1068 // we need to figure out include paths in the test.
1069 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1070 // "class Y { }; "
1071 // "void *operator new(size_t size) { return 0; } "
1072 // "Y *y = new Y;", OpCall));
1073 EXPECT_TRUE(notMatches("class Y { }; "
1074 "void operator delete(void *p) { } "
1075 "void a() {Y *y = new Y; delete y;}", OpCall));
1076 // Binary operator
1077 EXPECT_TRUE(matches("class Y { }; "
1078 "bool operator&&(Y x, Y y) { return true; }; "
1079 "Y a; Y b; bool c = a && b;",
1080 OpCall));
1081 // No match -- normal operator, not an overloaded one.
1082 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1083 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1084}
1085
1086TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1087 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001088 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001089 EXPECT_TRUE(matches("class Y { }; "
1090 "bool operator&&(Y x, Y y) { return true; }; "
1091 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1092 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001093 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001094 EXPECT_TRUE(notMatches("class Y { }; "
1095 "bool operator&&(Y x, Y y) { return true; }; "
1096 "Y a; Y b; bool c = a && b;",
1097 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001098 StatementMatcher OpStarCall =
1099 operatorCallExpr(hasOverloadedOperatorName("*"));
1100 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1101 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001102 DeclarationMatcher ClassWithOpStar =
1103 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1104 EXPECT_TRUE(matches("class Y { int operator*(); };",
1105 ClassWithOpStar));
1106 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1107 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001108 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1109 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1110 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001111}
1112
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001113TEST(Matcher, NestedOverloadedOperatorCalls) {
1114 EXPECT_TRUE(matchAndVerifyResultTrue(
1115 "class Y { }; "
1116 "Y& operator&&(Y& x, Y& y) { return x; }; "
1117 "Y a; Y b; Y c; Y d = a && b && c;",
1118 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1119 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1120 EXPECT_TRUE(matches(
1121 "class Y { }; "
1122 "Y& operator&&(Y& x, Y& y) { return x; }; "
1123 "Y a; Y b; Y c; Y d = a && b && c;",
1124 operatorCallExpr(hasParent(operatorCallExpr()))));
1125 EXPECT_TRUE(matches(
1126 "class Y { }; "
1127 "Y& operator&&(Y& x, Y& y) { return x; }; "
1128 "Y a; Y b; Y c; Y d = a && b && c;",
1129 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1130}
1131
Manuel Klimek04616e42012-07-06 05:48:52 +00001132TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001133 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001134 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001135
1136 EXPECT_TRUE(
1137 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1138 MethodOnY));
1139 EXPECT_TRUE(
1140 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1141 MethodOnY));
1142 EXPECT_TRUE(
1143 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1144 MethodOnY));
1145 EXPECT_TRUE(
1146 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1147 MethodOnY));
1148 EXPECT_TRUE(
1149 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1150 MethodOnY));
1151
1152 EXPECT_TRUE(matches(
1153 "class Y {"
1154 " public: virtual void x();"
1155 "};"
1156 "class X : public Y {"
1157 " public: virtual void x();"
1158 "};"
1159 "void z() { X *x; x->Y::x(); }", MethodOnY));
1160}
1161
1162TEST(Matcher, VariableUsage) {
1163 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001164 declRefExpr(to(
1165 varDecl(hasInitializer(
1166 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001167
1168 EXPECT_TRUE(matches(
1169 "class Y {"
1170 " public:"
1171 " bool x() const;"
1172 "};"
1173 "void z(const Y &y) {"
1174 " bool b = y.x();"
1175 " if (b) {}"
1176 "}", Reference));
1177
1178 EXPECT_TRUE(notMatches(
1179 "class Y {"
1180 " public:"
1181 " bool x() const;"
1182 "};"
1183 "void z(const Y &y) {"
1184 " bool b = y.x();"
1185 "}", Reference));
1186}
1187
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001188TEST(Matcher, VarDecl_Storage) {
1189 auto M = varDecl(hasName("X"), hasLocalStorage());
1190 EXPECT_TRUE(matches("void f() { int X; }", M));
1191 EXPECT_TRUE(notMatches("int X;", M));
1192 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1193
1194 M = varDecl(hasName("X"), hasGlobalStorage());
1195 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1196 EXPECT_TRUE(matches("int X;", M));
1197 EXPECT_TRUE(matches("void f() { static int X; }", M));
1198}
1199
Manuel Klimek61379422012-12-04 14:42:08 +00001200TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001201 EXPECT_TRUE(matches(
1202 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001203 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001204}
1205
Manuel Klimek04616e42012-07-06 05:48:52 +00001206TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001207 StatementMatcher CallOnVariableY =
1208 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001209
1210 EXPECT_TRUE(matches(
1211 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1212 EXPECT_TRUE(matches(
1213 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1214 EXPECT_TRUE(matches(
1215 "class Y { public: void x(); };"
1216 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1217 EXPECT_TRUE(matches(
1218 "class Y { public: void x(); };"
1219 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1220 EXPECT_TRUE(notMatches(
1221 "class Y { public: void x(); };"
1222 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1223 CallOnVariableY));
1224}
1225
Daniel Jasper1dad1832012-07-10 20:20:19 +00001226TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1227 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1228 unaryExprOrTypeTraitExpr()));
1229 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1230 alignOfExpr(anything())));
1231 // FIXME: Uncomment once alignof is enabled.
1232 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1233 // unaryExprOrTypeTraitExpr()));
1234 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1235 // sizeOfExpr()));
1236}
1237
1238TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1239 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1240 hasArgumentOfType(asString("int")))));
1241 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1242 hasArgumentOfType(asString("float")))));
1243 EXPECT_TRUE(matches(
1244 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001245 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001246 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001247 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001248}
1249
Manuel Klimek04616e42012-07-06 05:48:52 +00001250TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001251 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001252}
1253
1254TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001255 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001256}
1257
1258TEST(MemberExpression, MatchesVariable) {
1259 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001260 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001261 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001262 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001263 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001264 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001265}
1266
1267TEST(MemberExpression, MatchesStaticVariable) {
1268 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001269 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001270 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001271 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001272 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001273 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001274}
1275
Daniel Jasper4e566c42012-07-12 08:50:38 +00001276TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001277 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1278 EXPECT_TRUE(matches(
1279 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1280 callExpr(hasArgument(0, declRefExpr(
1281 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001282}
1283
1284TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001285 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001286 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001287 callExpr(hasArgument(0, declRefExpr(
1288 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001289}
1290
Manuel Klimek04616e42012-07-06 05:48:52 +00001291TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1292 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001293 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001294 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001295 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001296 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001297 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001298}
1299
1300TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1301 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001302 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001303 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001304 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001305 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001306 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001307}
1308
1309TEST(IsArrow, MatchesMemberCallsViaArrow) {
1310 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001311 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001312 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001313 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001314 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001315 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001316}
1317
1318TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001319 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001320
1321 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1322 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1323}
1324
1325TEST(Callee, MatchesMemberExpressions) {
1326 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001327 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001328 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001329 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001330}
1331
1332TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001333 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001334
1335 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1336 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1337
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001338 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1339 llvm::Triple::Win32) {
1340 // FIXME: Make this work for MSVC.
1341 // Dependent contexts, but a non-dependent call.
1342 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1343 CallFunctionF));
1344 EXPECT_TRUE(
1345 matches("void f(); template <int N> struct S { void g() { f(); } };",
1346 CallFunctionF));
1347 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001348
1349 // Depedent calls don't match.
1350 EXPECT_TRUE(
1351 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1352 CallFunctionF));
1353 EXPECT_TRUE(
1354 notMatches("void f(int);"
1355 "template <typename T> struct S { void g(T t) { f(t); } };",
1356 CallFunctionF));
1357}
1358
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001359TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1360 EXPECT_TRUE(
1361 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001362 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001363}
1364
1365TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1366 EXPECT_TRUE(
1367 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001368 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001369}
1370
1371TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1372 EXPECT_TRUE(
1373 notMatches("void g(); template <typename T> void f(T t) {}"
1374 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001375 functionTemplateDecl(hasName("f"),
1376 hasDescendant(declRefExpr(to(
1377 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001378}
1379
Manuel Klimek04616e42012-07-06 05:48:52 +00001380TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001381 StatementMatcher CallArgumentY = callExpr(
1382 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001383
1384 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1385 EXPECT_TRUE(
1386 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1387 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1388
Daniel Jasper848cbe12012-09-18 13:09:13 +00001389 StatementMatcher WrongIndex = callExpr(
1390 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001391 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1392}
1393
1394TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001395 StatementMatcher CallArgumentY = callExpr(
1396 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001397 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1398 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1399 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1400}
1401
1402TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001403 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001404
1405 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1406 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1407 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1408}
1409
Daniel Jasper9f501292012-12-04 11:54:27 +00001410TEST(Matcher, ParameterCount) {
1411 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1412 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1413 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1414 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1415 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1416}
1417
Manuel Klimek04616e42012-07-06 05:48:52 +00001418TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001419 DeclarationMatcher ReferenceClassX = varDecl(
1420 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001421 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1422 ReferenceClassX));
1423 EXPECT_TRUE(
1424 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001425 // The match here is on the implicit copy constructor code for
1426 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001427 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001428 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1429 EXPECT_TRUE(
1430 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001431 EXPECT_TRUE(
1432 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1433}
1434
Edwin Vane0a4836e2013-03-06 17:02:57 +00001435TEST(QualType, hasCanonicalType) {
1436 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1437 "int a;"
1438 "int_ref b = a;",
1439 varDecl(hasType(qualType(referenceType())))));
1440 EXPECT_TRUE(
1441 matches("typedef int &int_ref;"
1442 "int a;"
1443 "int_ref b = a;",
1444 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1445}
1446
Edwin Vane119d3df2013-04-02 18:15:55 +00001447TEST(QualType, hasLocalQualifiers) {
1448 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1449 varDecl(hasType(hasLocalQualifiers()))));
1450 EXPECT_TRUE(matches("int *const j = nullptr;",
1451 varDecl(hasType(hasLocalQualifiers()))));
1452 EXPECT_TRUE(matches("int *volatile k;",
1453 varDecl(hasType(hasLocalQualifiers()))));
1454 EXPECT_TRUE(notMatches("int m;",
1455 varDecl(hasType(hasLocalQualifiers()))));
1456}
1457
Manuel Klimek04616e42012-07-06 05:48:52 +00001458TEST(HasParameter, CallsInnerMatcher) {
1459 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001460 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001461 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001462 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001463}
1464
1465TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1466 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001467 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001468}
1469
1470TEST(HasType, MatchesParameterVariableTypesStrictly) {
1471 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001472 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001473 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001474 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001475 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001476 methodDecl(hasParameter(0,
1477 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001478 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001479 methodDecl(hasParameter(0,
1480 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001481}
1482
1483TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1484 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001485 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001486 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001487 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001488}
1489
Daniel Jasper1dad1832012-07-10 20:20:19 +00001490TEST(Returns, MatchesReturnTypes) {
1491 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001492 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001493 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001494 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001495 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001496 functionDecl(returns(hasDeclaration(
1497 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001498}
1499
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001500TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001501 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1502 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1503 functionDecl(isExternC())));
1504 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001505}
1506
Manuel Klimek04616e42012-07-06 05:48:52 +00001507TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1508 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001509 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001510}
1511
1512TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1513 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001514 methodDecl(hasAnyParameter(hasType(pointsTo(
1515 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001516}
1517
Alp Toker8db6e7a2014-01-05 06:38:57 +00001518TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001519 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001520 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001521 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001522 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001523}
1524
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001525TEST(Matcher, MatchesClassTemplateSpecialization) {
1526 EXPECT_TRUE(matches("template<typename T> struct A {};"
1527 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001528 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001529 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001530 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001531 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001532 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001533}
1534
Manuel Klimekc16c6522013-06-20 13:08:29 +00001535TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1536 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1537 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1538}
1539
1540TEST(ParmVarDecl, MatchesParmVars) {
1541 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1542 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1543}
1544
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001545TEST(Matcher, MatchesTypeTemplateArgument) {
1546 EXPECT_TRUE(matches(
1547 "template<typename T> struct B {};"
1548 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001549 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001550 asString("int"))))));
1551}
1552
1553TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1554 EXPECT_TRUE(matches(
1555 "struct B { int next; };"
1556 "template<int(B::*next_ptr)> struct A {};"
1557 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001558 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1559 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001560
1561 EXPECT_TRUE(notMatches(
1562 "template <typename T> struct A {};"
1563 "A<int> a;",
1564 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1565 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001566
1567 EXPECT_TRUE(matches(
1568 "struct B { int next; };"
1569 "template<int(B::*next_ptr)> struct A {};"
1570 "A<&B::next> a;",
1571 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1572 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1573
1574 EXPECT_TRUE(notMatches(
1575 "template <typename T> struct A {};"
1576 "A<int> a;",
1577 templateSpecializationType(hasAnyTemplateArgument(
1578 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001579}
1580
1581TEST(Matcher, MatchesSpecificArgument) {
1582 EXPECT_TRUE(matches(
1583 "template<typename T, typename U> class A {};"
1584 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001585 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001586 1, refersToType(asString("int"))))));
1587 EXPECT_TRUE(notMatches(
1588 "template<typename T, typename U> class A {};"
1589 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001590 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001591 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001592
1593 EXPECT_TRUE(matches(
1594 "template<typename T, typename U> class A {};"
1595 "A<bool, int> a;",
1596 templateSpecializationType(hasTemplateArgument(
1597 1, refersToType(asString("int"))))));
1598 EXPECT_TRUE(notMatches(
1599 "template<typename T, typename U> class A {};"
1600 "A<int, bool> a;",
1601 templateSpecializationType(hasTemplateArgument(
1602 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001603}
1604
Daniel Jasper639522c2013-02-25 12:02:08 +00001605TEST(Matcher, MatchesAccessSpecDecls) {
1606 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1607 EXPECT_TRUE(
1608 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1609 EXPECT_TRUE(
1610 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1611 EXPECT_TRUE(
1612 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1613
1614 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1615}
1616
Edwin Vane37ee1d72013-04-09 20:46:36 +00001617TEST(Matcher, MatchesVirtualMethod) {
1618 EXPECT_TRUE(matches("class X { virtual int f(); };",
1619 methodDecl(isVirtual(), hasName("::X::f"))));
1620 EXPECT_TRUE(notMatches("class X { int f(); };",
1621 methodDecl(isVirtual())));
1622}
1623
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001624TEST(Matcher, MatchesPureMethod) {
1625 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1626 methodDecl(isPure(), hasName("::X::f"))));
1627 EXPECT_TRUE(notMatches("class X { int f(); };",
1628 methodDecl(isPure())));
1629}
1630
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001631TEST(Matcher, MatchesConstMethod) {
1632 EXPECT_TRUE(matches("struct A { void foo() const; };",
1633 methodDecl(isConst())));
1634 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1635 methodDecl(isConst())));
1636}
1637
Edwin Vane37ee1d72013-04-09 20:46:36 +00001638TEST(Matcher, MatchesOverridingMethod) {
1639 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1640 "class Y : public X { int f(); };",
1641 methodDecl(isOverride(), hasName("::Y::f"))));
1642 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1643 "class Y : public X { int f(); };",
1644 methodDecl(isOverride(), hasName("::X::f"))));
1645 EXPECT_TRUE(notMatches("class X { int f(); }; "
1646 "class Y : public X { int f(); };",
1647 methodDecl(isOverride())));
1648 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1649 methodDecl(isOverride())));
1650}
1651
Manuel Klimek04616e42012-07-06 05:48:52 +00001652TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001653 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001654
1655 EXPECT_TRUE(
1656 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1657 EXPECT_TRUE(
1658 matches("class X { public: X(); }; void x() { X x = X(); }",
1659 Constructor));
1660 EXPECT_TRUE(
1661 matches("class X { public: X(int); }; void x() { X x = 0; }",
1662 Constructor));
1663 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1664}
1665
1666TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001667 StatementMatcher Constructor = constructExpr(
1668 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001669
1670 EXPECT_TRUE(
1671 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1672 Constructor));
1673 EXPECT_TRUE(
1674 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1675 Constructor));
1676 EXPECT_TRUE(
1677 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1678 Constructor));
1679 EXPECT_TRUE(
1680 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1681 Constructor));
1682
Daniel Jasper848cbe12012-09-18 13:09:13 +00001683 StatementMatcher WrongIndex = constructExpr(
1684 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001685 EXPECT_TRUE(
1686 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1687 WrongIndex));
1688}
1689
1690TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001691 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001692
1693 EXPECT_TRUE(
1694 matches("class X { public: X(int); }; void x() { X x(0); }",
1695 Constructor1Arg));
1696 EXPECT_TRUE(
1697 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1698 Constructor1Arg));
1699 EXPECT_TRUE(
1700 matches("class X { public: X(int); }; void x() { X x = 0; }",
1701 Constructor1Arg));
1702 EXPECT_TRUE(
1703 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1704 Constructor1Arg));
1705}
1706
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001707TEST(Matcher, ConstructorListInitialization) {
1708 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1709
1710 EXPECT_TRUE(
1711 matches("class X { public: X(int); }; void x() { X x{0}; }",
1712 ConstructorListInit));
1713 EXPECT_FALSE(
1714 matches("class X { public: X(int); }; void x() { X x(0); }",
1715 ConstructorListInit));
1716}
1717
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001718TEST(Matcher,ThisExpr) {
1719 EXPECT_TRUE(
1720 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1721 EXPECT_TRUE(
1722 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1723}
1724
Manuel Klimek04616e42012-07-06 05:48:52 +00001725TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001726 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001727
1728 std::string ClassString = "class string { public: string(); ~string(); }; ";
1729
1730 EXPECT_TRUE(
1731 matches(ClassString +
1732 "string GetStringByValue();"
1733 "void FunctionTakesString(string s);"
1734 "void run() { FunctionTakesString(GetStringByValue()); }",
1735 TempExpression));
1736
1737 EXPECT_TRUE(
1738 notMatches(ClassString +
1739 "string* GetStringPointer(); "
1740 "void FunctionTakesStringPtr(string* s);"
1741 "void run() {"
1742 " string* s = GetStringPointer();"
1743 " FunctionTakesStringPtr(GetStringPointer());"
1744 " FunctionTakesStringPtr(s);"
1745 "}",
1746 TempExpression));
1747
1748 EXPECT_TRUE(
1749 notMatches("class no_dtor {};"
1750 "no_dtor GetObjByValue();"
1751 "void ConsumeObj(no_dtor param);"
1752 "void run() { ConsumeObj(GetObjByValue()); }",
1753 TempExpression));
1754}
1755
Sam Panzer68a35af2012-08-24 22:04:44 +00001756TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1757 std::string ClassString =
1758 "class string { public: string(); int length(); }; ";
1759
1760 EXPECT_TRUE(
1761 matches(ClassString +
1762 "string GetStringByValue();"
1763 "void FunctionTakesString(string s);"
1764 "void run() { FunctionTakesString(GetStringByValue()); }",
1765 materializeTemporaryExpr()));
1766
1767 EXPECT_TRUE(
1768 notMatches(ClassString +
1769 "string* GetStringPointer(); "
1770 "void FunctionTakesStringPtr(string* s);"
1771 "void run() {"
1772 " string* s = GetStringPointer();"
1773 " FunctionTakesStringPtr(GetStringPointer());"
1774 " FunctionTakesStringPtr(s);"
1775 "}",
1776 materializeTemporaryExpr()));
1777
1778 EXPECT_TRUE(
1779 notMatches(ClassString +
1780 "string GetStringByValue();"
1781 "void run() { int k = GetStringByValue().length(); }",
1782 materializeTemporaryExpr()));
1783
1784 EXPECT_TRUE(
1785 notMatches(ClassString +
1786 "string GetStringByValue();"
1787 "void run() { GetStringByValue(); }",
1788 materializeTemporaryExpr()));
1789}
1790
Manuel Klimek04616e42012-07-06 05:48:52 +00001791TEST(ConstructorDeclaration, SimpleCase) {
1792 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001793 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001794 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001795 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001796}
1797
1798TEST(ConstructorDeclaration, IsImplicit) {
1799 // This one doesn't match because the constructor is not added by the
1800 // compiler (it is not needed).
1801 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001802 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001803 // The compiler added the implicit default constructor.
1804 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001805 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001806 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001807 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001808 // The compiler added an implicit assignment operator.
1809 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1810 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001811}
1812
Daniel Jasper1dad1832012-07-10 20:20:19 +00001813TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1814 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001815 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001816}
1817
1818TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001819 EXPECT_TRUE(notMatches("class Foo {};",
1820 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001821}
1822
Manuel Klimek04616e42012-07-06 05:48:52 +00001823TEST(HasAnyConstructorInitializer, SimpleCase) {
1824 EXPECT_TRUE(notMatches(
1825 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001826 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001827 EXPECT_TRUE(matches(
1828 "class Foo {"
1829 " Foo() : foo_() { }"
1830 " int foo_;"
1831 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001832 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001833}
1834
1835TEST(HasAnyConstructorInitializer, ForField) {
1836 static const char Code[] =
1837 "class Baz { };"
1838 "class Foo {"
1839 " Foo() : foo_() { }"
1840 " Baz foo_;"
1841 " Baz bar_;"
1842 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001843 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1844 forField(hasType(recordDecl(hasName("Baz"))))))));
1845 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001846 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001847 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1848 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001849}
1850
1851TEST(HasAnyConstructorInitializer, WithInitializer) {
1852 static const char Code[] =
1853 "class Foo {"
1854 " Foo() : foo_(0) { }"
1855 " int foo_;"
1856 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001857 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001858 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001859 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001860 withInitializer(integerLiteral(equals(1)))))));
1861}
1862
1863TEST(HasAnyConstructorInitializer, IsWritten) {
1864 static const char Code[] =
1865 "struct Bar { Bar(){} };"
1866 "class Foo {"
1867 " Foo() : foo_() { }"
1868 " Bar foo_;"
1869 " Bar bar_;"
1870 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001871 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001872 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001873 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001874 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001875 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001876 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1877}
1878
1879TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001880 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001881
1882 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
1883 EXPECT_TRUE(
1884 matches("class X { public: X(); }; void x() { new X(); }", New));
1885 EXPECT_TRUE(
1886 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1887 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
1888}
1889
1890TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001891 StatementMatcher New = constructExpr(
1892 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001893
1894 EXPECT_TRUE(
1895 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1896 New));
1897 EXPECT_TRUE(
1898 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1899 New));
1900 EXPECT_TRUE(
1901 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
1902 New));
1903
Daniel Jasper848cbe12012-09-18 13:09:13 +00001904 StatementMatcher WrongIndex = constructExpr(
1905 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001906 EXPECT_TRUE(
1907 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
1908 WrongIndex));
1909}
1910
1911TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001912 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001913
1914 EXPECT_TRUE(
1915 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1916 EXPECT_TRUE(
1917 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
1918 New));
1919}
1920
Daniel Jasper1dad1832012-07-10 20:20:19 +00001921TEST(Matcher, DeleteExpression) {
1922 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001923 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001924}
1925
Manuel Klimek04616e42012-07-06 05:48:52 +00001926TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001927 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001928
1929 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
1930 EXPECT_TRUE(
1931 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
1932 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
1933}
1934
1935TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001936 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001937 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
1938 // wide string
1939 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
1940 // with escaped characters
1941 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
1942 // no matching -- though the data type is the same, there is no string literal
1943 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
1944}
1945
1946TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001947 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001948 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
1949 // wide character
1950 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
1951 // wide character, Hex encoded, NOT MATCHED!
1952 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
1953 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
1954}
1955
1956TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001957 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001958 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
1959 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
1960 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
1961 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
1962
1963 // Non-matching cases (character literals, float and double)
1964 EXPECT_TRUE(notMatches("int i = L'a';",
1965 HasIntLiteral)); // this is actually a character
1966 // literal cast to int
1967 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
1968 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
1969 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
1970}
1971
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00001972TEST(Matcher, FloatLiterals) {
1973 StatementMatcher HasFloatLiteral = floatLiteral();
1974 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
1975 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
1976 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
1977 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
1978 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
1979
1980 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
1981}
1982
Daniel Jasper5901e472012-10-01 13:40:41 +00001983TEST(Matcher, NullPtrLiteral) {
1984 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
1985}
1986
Daniel Jasper87c3d362012-09-20 14:12:57 +00001987TEST(Matcher, AsmStatement) {
1988 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1989}
1990
Manuel Klimek04616e42012-07-06 05:48:52 +00001991TEST(Matcher, Conditions) {
1992 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
1993
1994 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
1995 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
1996 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
1997 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
1998 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
1999}
2000
Manuel Klimek909b5c942014-05-27 10:04:12 +00002001TEST(IfStmt, ChildTraversalMatchers) {
2002 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2003 ifStmt(hasThen(boolLiteral(equals(true))))));
2004 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2005 ifStmt(hasThen(boolLiteral(equals(true))))));
2006 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2007 ifStmt(hasElse(boolLiteral(equals(true))))));
2008 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2009 ifStmt(hasElse(boolLiteral(equals(true))))));
2010}
2011
Manuel Klimek04616e42012-07-06 05:48:52 +00002012TEST(MatchBinaryOperator, HasOperatorName) {
2013 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2014
2015 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2016 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2017}
2018
2019TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2020 StatementMatcher OperatorTrueFalse =
2021 binaryOperator(hasLHS(boolLiteral(equals(true))),
2022 hasRHS(boolLiteral(equals(false))));
2023
2024 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2025 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2026 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2027}
2028
2029TEST(MatchBinaryOperator, HasEitherOperand) {
2030 StatementMatcher HasOperand =
2031 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2032
2033 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2034 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2035 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2036}
2037
2038TEST(Matcher, BinaryOperatorTypes) {
2039 // Integration test that verifies the AST provides all binary operators in
2040 // a way we expect.
2041 // FIXME: Operator ','
2042 EXPECT_TRUE(
2043 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2044 EXPECT_TRUE(
2045 matches("bool b; bool c = (b = true);",
2046 binaryOperator(hasOperatorName("="))));
2047 EXPECT_TRUE(
2048 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2049 EXPECT_TRUE(
2050 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2051 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2052 EXPECT_TRUE(
2053 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2054 EXPECT_TRUE(
2055 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2056 EXPECT_TRUE(
2057 matches("int i = 1; int j = (i <<= 2);",
2058 binaryOperator(hasOperatorName("<<="))));
2059 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2060 EXPECT_TRUE(
2061 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2062 EXPECT_TRUE(
2063 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2064 EXPECT_TRUE(
2065 matches("int i = 1; int j = (i >>= 2);",
2066 binaryOperator(hasOperatorName(">>="))));
2067 EXPECT_TRUE(
2068 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2069 EXPECT_TRUE(
2070 matches("int i = 42; int j = (i ^= 42);",
2071 binaryOperator(hasOperatorName("^="))));
2072 EXPECT_TRUE(
2073 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2074 EXPECT_TRUE(
2075 matches("int i = 42; int j = (i %= 42);",
2076 binaryOperator(hasOperatorName("%="))));
2077 EXPECT_TRUE(
2078 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2079 EXPECT_TRUE(
2080 matches("bool b = true && false;",
2081 binaryOperator(hasOperatorName("&&"))));
2082 EXPECT_TRUE(
2083 matches("bool b = true; bool c = (b &= false);",
2084 binaryOperator(hasOperatorName("&="))));
2085 EXPECT_TRUE(
2086 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2087 EXPECT_TRUE(
2088 matches("bool b = true || false;",
2089 binaryOperator(hasOperatorName("||"))));
2090 EXPECT_TRUE(
2091 matches("bool b = true; bool c = (b |= false);",
2092 binaryOperator(hasOperatorName("|="))));
2093 EXPECT_TRUE(
2094 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2095 EXPECT_TRUE(
2096 matches("int i = 42; int j = (i *= 23);",
2097 binaryOperator(hasOperatorName("*="))));
2098 EXPECT_TRUE(
2099 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2100 EXPECT_TRUE(
2101 matches("int i = 42; int j = (i /= 23);",
2102 binaryOperator(hasOperatorName("/="))));
2103 EXPECT_TRUE(
2104 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2105 EXPECT_TRUE(
2106 matches("int i = 42; int j = (i += 23);",
2107 binaryOperator(hasOperatorName("+="))));
2108 EXPECT_TRUE(
2109 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2110 EXPECT_TRUE(
2111 matches("int i = 42; int j = (i -= 23);",
2112 binaryOperator(hasOperatorName("-="))));
2113 EXPECT_TRUE(
2114 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2115 binaryOperator(hasOperatorName("->*"))));
2116 EXPECT_TRUE(
2117 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2118 binaryOperator(hasOperatorName(".*"))));
2119
2120 // Member expressions as operators are not supported in matches.
2121 EXPECT_TRUE(
2122 notMatches("struct A { void x(A *a) { a->x(this); } };",
2123 binaryOperator(hasOperatorName("->"))));
2124
2125 // Initializer assignments are not represented as operator equals.
2126 EXPECT_TRUE(
2127 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2128
2129 // Array indexing is not represented as operator.
2130 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2131
2132 // Overloaded operators do not match at all.
2133 EXPECT_TRUE(notMatches(
2134 "struct A { bool operator&&(const A &a) const { return false; } };"
2135 "void x() { A a, b; a && b; }",
2136 binaryOperator()));
2137}
2138
2139TEST(MatchUnaryOperator, HasOperatorName) {
2140 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2141
2142 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2143 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2144}
2145
2146TEST(MatchUnaryOperator, HasUnaryOperand) {
2147 StatementMatcher OperatorOnFalse =
2148 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2149
2150 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2151 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2152}
2153
2154TEST(Matcher, UnaryOperatorTypes) {
2155 // Integration test that verifies the AST provides all unary operators in
2156 // a way we expect.
2157 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2158 EXPECT_TRUE(
2159 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2160 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2161 EXPECT_TRUE(
2162 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2163 EXPECT_TRUE(
2164 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2165 EXPECT_TRUE(
2166 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2167 EXPECT_TRUE(
2168 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2169 EXPECT_TRUE(
2170 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2171 EXPECT_TRUE(
2172 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2173 EXPECT_TRUE(
2174 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2175
2176 // We don't match conversion operators.
2177 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2178
2179 // Function calls are not represented as operator.
2180 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2181
2182 // Overloaded operators do not match at all.
2183 // FIXME: We probably want to add that.
2184 EXPECT_TRUE(notMatches(
2185 "struct A { bool operator!() const { return false; } };"
2186 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2187}
2188
2189TEST(Matcher, ConditionalOperator) {
2190 StatementMatcher Conditional = conditionalOperator(
2191 hasCondition(boolLiteral(equals(true))),
2192 hasTrueExpression(boolLiteral(equals(false))));
2193
2194 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2195 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2196 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2197
2198 StatementMatcher ConditionalFalse = conditionalOperator(
2199 hasFalseExpression(boolLiteral(equals(false))));
2200
2201 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2202 EXPECT_TRUE(
2203 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2204}
2205
Daniel Jasper1dad1832012-07-10 20:20:19 +00002206TEST(ArraySubscriptMatchers, ArraySubscripts) {
2207 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2208 arraySubscriptExpr()));
2209 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2210 arraySubscriptExpr()));
2211}
2212
2213TEST(ArraySubscriptMatchers, ArrayIndex) {
2214 EXPECT_TRUE(matches(
2215 "int i[2]; void f() { i[1] = 1; }",
2216 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2217 EXPECT_TRUE(matches(
2218 "int i[2]; void f() { 1[i] = 1; }",
2219 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2220 EXPECT_TRUE(notMatches(
2221 "int i[2]; void f() { i[1] = 1; }",
2222 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2223}
2224
2225TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2226 EXPECT_TRUE(matches(
2227 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002228 arraySubscriptExpr(hasBase(implicitCastExpr(
2229 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002230}
2231
Manuel Klimek04616e42012-07-06 05:48:52 +00002232TEST(Matcher, HasNameSupportsNamespaces) {
2233 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002234 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002235 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002236 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002237 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002238 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002239 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002240 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002241 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002242 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002243 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002244 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002245 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002246 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002247 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002248 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002249 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002250 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002251 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002252 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002253 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002254 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002255 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002256 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002257}
2258
2259TEST(Matcher, HasNameSupportsOuterClasses) {
2260 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002261 matches("class A { class B { class C; }; };",
2262 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002263 EXPECT_TRUE(
2264 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002265 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002266 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002267 matches("class A { class B { class C; }; };",
2268 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002269 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002270 matches("class A { class B { class C; }; };",
2271 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002272 EXPECT_TRUE(
2273 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002274 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002275 EXPECT_TRUE(
2276 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002277 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002278 EXPECT_TRUE(
2279 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002280 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002281 EXPECT_TRUE(
2282 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002283 recordDecl(hasName("::C"))));
2284 EXPECT_TRUE(
2285 notMatches("class A { class B { class C; }; };",
2286 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002287 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002288 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002289 EXPECT_TRUE(
2290 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002291 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002292}
2293
2294TEST(Matcher, IsDefinition) {
2295 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002296 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002297 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2298 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2299
2300 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002301 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002302 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2303 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2304
2305 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002306 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002307 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2308 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2309}
2310
2311TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002312 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002313 ofClass(hasName("X")))));
2314
2315 EXPECT_TRUE(
2316 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2317 EXPECT_TRUE(
2318 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2319 Constructor));
2320 EXPECT_TRUE(
2321 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2322 Constructor));
2323}
2324
2325TEST(Matcher, VisitsTemplateInstantiations) {
2326 EXPECT_TRUE(matches(
2327 "class A { public: void x(); };"
2328 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002329 "void f() { B<A> b; b.y(); }",
2330 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002331
2332 EXPECT_TRUE(matches(
2333 "class A { public: void x(); };"
2334 "class C {"
2335 " public:"
2336 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2337 "};"
2338 "void f() {"
2339 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002340 "}",
2341 recordDecl(hasName("C"),
2342 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002343}
2344
Daniel Jasper1dad1832012-07-10 20:20:19 +00002345TEST(Matcher, HandlesNullQualTypes) {
2346 // FIXME: Add a Type matcher so we can replace uses of this
2347 // variable with Type(True())
2348 const TypeMatcher AnyType = anything();
2349
2350 // We don't really care whether this matcher succeeds; we're testing that
2351 // it completes without crashing.
2352 EXPECT_TRUE(matches(
2353 "struct A { };"
2354 "template <typename T>"
2355 "void f(T t) {"
2356 " T local_t(t /* this becomes a null QualType in the AST */);"
2357 "}"
2358 "void g() {"
2359 " f(0);"
2360 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002361 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002362 anyOf(
2363 TypeMatcher(hasDeclaration(anything())),
2364 pointsTo(AnyType),
2365 references(AnyType)
2366 // Other QualType matchers should go here.
2367 ))))));
2368}
2369
Manuel Klimek04616e42012-07-06 05:48:52 +00002370// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002371AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002372 // Make sure all special variables are used: node, match_finder,
2373 // bound_nodes_builder, and the parameter named 'AMatcher'.
2374 return AMatcher.matches(Node, Finder, Builder);
2375}
2376
2377TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002378 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002379
2380 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002381 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002382
2383 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002384 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002385
2386 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002387 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002388}
2389
2390AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +00002391 polymorphicHas,
2392 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2393 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002394 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002395 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002396 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2397 ASTMatchFinder::BK_First);
2398}
2399
2400TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002401 DeclarationMatcher HasClassB =
2402 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002403
2404 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002405 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002406
2407 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002408 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002409
2410 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002411 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002412
2413 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002414 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002415
2416 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2417}
2418
2419TEST(For, FindsForLoops) {
2420 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2421 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002422 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2423 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002424 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002425}
2426
Daniel Jasper4e566c42012-07-12 08:50:38 +00002427TEST(For, ForLoopInternals) {
2428 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2429 forStmt(hasCondition(anything()))));
2430 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2431 forStmt(hasLoopInit(anything()))));
2432}
2433
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002434TEST(For, ForRangeLoopInternals) {
2435 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2436 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002437 EXPECT_TRUE(matches(
2438 "void f(){ int a[] {1, 2}; for (int i : a); }",
2439 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002440}
2441
Daniel Jasper4e566c42012-07-12 08:50:38 +00002442TEST(For, NegativeForLoopInternals) {
2443 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002444 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002445 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2446 forStmt(hasLoopInit(anything()))));
2447}
2448
Manuel Klimek04616e42012-07-06 05:48:52 +00002449TEST(For, ReportsNoFalsePositives) {
2450 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2451 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2452}
2453
2454TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002455 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2456 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2457 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002458}
2459
2460TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2461 // It's not a compound statement just because there's "{}" in the source
2462 // text. This is an AST search, not grep.
2463 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002464 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002465 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002466 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002467}
2468
Daniel Jasper4e566c42012-07-12 08:50:38 +00002469TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002470 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002471 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002472 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002473 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002474 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002475 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002476 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002477 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002478 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2479 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002480}
2481
2482TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2483 // The simplest case: every compound statement is in a function
2484 // definition, and the function body itself must be a compound
2485 // statement.
2486 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002487 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002488}
2489
2490TEST(HasAnySubstatement, IsNotRecursive) {
2491 // It's really "has any immediate substatement".
2492 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002493 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002494}
2495
2496TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2497 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002498 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002499}
2500
2501TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2502 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002503 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002504}
2505
2506TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2507 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002508 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002509 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002510 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002511}
2512
2513TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2514 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002515 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002516 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002517 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002518 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002519 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002520}
2521
2522TEST(StatementCountIs, WorksWithMultipleStatements) {
2523 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002524 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002525}
2526
2527TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2528 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002529 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002530 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002531 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002532 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002533 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002534 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002535 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002536}
2537
2538TEST(Member, WorksInSimplestCase) {
2539 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002540 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002541}
2542
2543TEST(Member, DoesNotMatchTheBaseExpression) {
2544 // Don't pick out the wrong part of the member expression, this should
2545 // be checking the member (name) only.
2546 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002547 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002548}
2549
2550TEST(Member, MatchesInMemberFunctionCall) {
2551 EXPECT_TRUE(matches("void f() {"
2552 " struct { void first() {}; } s;"
2553 " s.first();"
2554 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002555 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002556}
2557
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002558TEST(Member, MatchesMember) {
2559 EXPECT_TRUE(matches(
2560 "struct A { int i; }; void f() { A a; a.i = 2; }",
2561 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2562 EXPECT_TRUE(notMatches(
2563 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2564 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2565}
2566
Daniel Jasper639522c2013-02-25 12:02:08 +00002567TEST(Member, UnderstandsAccess) {
2568 EXPECT_TRUE(matches(
2569 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2570 EXPECT_TRUE(notMatches(
2571 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2572 EXPECT_TRUE(notMatches(
2573 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2574
2575 EXPECT_TRUE(notMatches(
2576 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2577 EXPECT_TRUE(notMatches(
2578 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2579 EXPECT_TRUE(matches(
2580 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2581
2582 EXPECT_TRUE(notMatches(
2583 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2584 EXPECT_TRUE(matches("class A { protected: int i; };",
2585 fieldDecl(isProtected(), hasName("i"))));
2586 EXPECT_TRUE(notMatches(
2587 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2588
2589 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2590 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2591 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2592 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2593}
2594
Dmitri Gribenko06963042012-08-18 00:29:27 +00002595TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002596 // Fails in C++11 mode
2597 EXPECT_TRUE(matchesConditionally(
2598 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2599 "class X { void *operator new(std::size_t); };",
2600 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002601
2602 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002603 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002604
Daniel Jasper5901e472012-10-01 13:40:41 +00002605 // Fails in C++11 mode
2606 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002607 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2608 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002609 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002610}
2611
Manuel Klimek04616e42012-07-06 05:48:52 +00002612TEST(HasObjectExpression, DoesNotMatchMember) {
2613 EXPECT_TRUE(notMatches(
2614 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002615 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002616}
2617
2618TEST(HasObjectExpression, MatchesBaseOfVariable) {
2619 EXPECT_TRUE(matches(
2620 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002621 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002622 EXPECT_TRUE(matches(
2623 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002624 memberExpr(hasObjectExpression(
2625 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002626}
2627
2628TEST(HasObjectExpression,
2629 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2630 EXPECT_TRUE(matches(
2631 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002632 memberExpr(hasObjectExpression(
2633 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002634 EXPECT_TRUE(matches(
2635 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002636 memberExpr(hasObjectExpression(
2637 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002638}
2639
2640TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002641 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2642 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2643 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2644 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002645}
2646
2647TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002648 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002649}
2650
2651TEST(IsConstQualified, MatchesConstInt) {
2652 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002653 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002654}
2655
2656TEST(IsConstQualified, MatchesConstPointer) {
2657 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002658 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002659}
2660
2661TEST(IsConstQualified, MatchesThroughTypedef) {
2662 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002663 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002664 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002665 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002666}
2667
2668TEST(IsConstQualified, DoesNotMatchInappropriately) {
2669 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002670 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002671 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002672 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002673}
2674
Sam Panzer80c13772012-08-16 16:58:10 +00002675TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002676 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2677 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2678 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2679 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002680}
2681TEST(CastExpression, MatchesImplicitCasts) {
2682 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002683 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002684 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002685 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002686}
2687
2688TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002689 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2690 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2691 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2692 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002693}
2694
Manuel Klimek04616e42012-07-06 05:48:52 +00002695TEST(ReinterpretCast, MatchesSimpleCase) {
2696 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002697 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002698}
2699
2700TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002701 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002702 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002703 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002704 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002705 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002706 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2707 "B b;"
2708 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002709 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002710}
2711
2712TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002713 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002714 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002715 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002716}
2717
2718TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002719 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002720 EXPECT_TRUE(
2721 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002722 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002723 EXPECT_TRUE(
2724 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002725 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002726}
2727
2728TEST(DynamicCast, MatchesSimpleCase) {
2729 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2730 "B b;"
2731 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002732 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002733}
2734
2735TEST(StaticCast, MatchesSimpleCase) {
2736 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002737 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002738}
2739
2740TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002741 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002742 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002743 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002744 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002745 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002746 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2747 "B b;"
2748 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002749 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002750}
2751
Daniel Jasper417f7762012-09-18 13:36:17 +00002752TEST(CStyleCast, MatchesSimpleCase) {
2753 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2754}
2755
2756TEST(CStyleCast, DoesNotMatchOtherCasts) {
2757 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2758 "char q, *r = const_cast<char*>(&q);"
2759 "void* s = reinterpret_cast<char*>(&s);"
2760 "struct B { virtual ~B() {} }; struct D : B {};"
2761 "B b;"
2762 "D* t = dynamic_cast<D*>(&b);",
2763 cStyleCastExpr()));
2764}
2765
Manuel Klimek04616e42012-07-06 05:48:52 +00002766TEST(HasDestinationType, MatchesSimpleCase) {
2767 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002768 staticCastExpr(hasDestinationType(
2769 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002770}
2771
Sam Panzer80c13772012-08-16 16:58:10 +00002772TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2773 // This test creates an implicit const cast.
2774 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002775 implicitCastExpr(
2776 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002777 // This test creates an implicit array-to-pointer cast.
2778 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002779 implicitCastExpr(hasImplicitDestinationType(
2780 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002781}
2782
2783TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2784 // This test creates an implicit cast from int to char.
2785 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002786 implicitCastExpr(hasImplicitDestinationType(
2787 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002788 // This test creates an implicit array-to-pointer cast.
2789 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002790 implicitCastExpr(hasImplicitDestinationType(
2791 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002792}
2793
2794TEST(ImplicitCast, MatchesSimpleCase) {
2795 // This test creates an implicit const cast.
2796 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002797 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002798 // This test creates an implicit cast from int to char.
2799 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002800 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002801 // This test creates an implicit array-to-pointer cast.
2802 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002803 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002804}
2805
2806TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002807 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002808 // are present, and that it ignores explicit and paren casts.
2809
2810 // These two test cases have no casts.
2811 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002812 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002813 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002814 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002815
2816 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002817 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002818 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002819 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002820
2821 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002822 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002823}
2824
2825TEST(IgnoringImpCasts, MatchesImpCasts) {
2826 // This test checks that ignoringImpCasts matches when implicit casts are
2827 // present and its inner matcher alone does not match.
2828 // Note that this test creates an implicit const cast.
2829 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002830 varDecl(hasInitializer(ignoringImpCasts(
2831 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002832 // This test creates an implict cast from int to char.
2833 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002834 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002835 integerLiteral(equals(0)))))));
2836}
2837
2838TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2839 // These tests verify that ignoringImpCasts does not match if the inner
2840 // matcher does not match.
2841 // Note that the first test creates an implicit const cast.
2842 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002843 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002844 unless(anything()))))));
2845 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002846 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002847 unless(anything()))))));
2848
2849 // These tests verify that ignoringImplictCasts does not look through explicit
2850 // casts or parentheses.
2851 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002852 varDecl(hasInitializer(ignoringImpCasts(
2853 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002854 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002855 varDecl(hasInitializer(ignoringImpCasts(
2856 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002857 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002858 varDecl(hasInitializer(ignoringImpCasts(
2859 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002860 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002861 varDecl(hasInitializer(ignoringImpCasts(
2862 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002863}
2864
2865TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2866 // This test verifies that expressions that do not have implicit casts
2867 // still match the inner matcher.
2868 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002869 varDecl(hasInitializer(ignoringImpCasts(
2870 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002871}
2872
2873TEST(IgnoringParenCasts, MatchesParenCasts) {
2874 // This test checks that ignoringParenCasts matches when parentheses and/or
2875 // casts are present and its inner matcher alone does not match.
2876 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002877 varDecl(hasInitializer(ignoringParenCasts(
2878 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002879 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002880 varDecl(hasInitializer(ignoringParenCasts(
2881 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002882
2883 // This test creates an implict cast from int to char in addition to the
2884 // parentheses.
2885 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002886 varDecl(hasInitializer(ignoringParenCasts(
2887 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002888
2889 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002890 varDecl(hasInitializer(ignoringParenCasts(
2891 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002892 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002893 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002894 integerLiteral(equals(0)))))));
2895}
2896
2897TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
2898 // This test verifies that expressions that do not have any casts still match.
2899 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002900 varDecl(hasInitializer(ignoringParenCasts(
2901 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002902}
2903
2904TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
2905 // These tests verify that ignoringImpCasts does not match if the inner
2906 // matcher does not match.
2907 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002908 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002909 unless(anything()))))));
2910
2911 // This test creates an implicit cast from int to char in addition to the
2912 // parentheses.
2913 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002914 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002915 unless(anything()))))));
2916
2917 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002918 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002919 unless(anything()))))));
2920}
2921
2922TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
2923 // This test checks that ignoringParenAndImpCasts matches when
2924 // parentheses and/or implicit casts are present and its inner matcher alone
2925 // does not match.
2926 // Note that this test creates an implicit const cast.
2927 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002928 varDecl(hasInitializer(ignoringParenImpCasts(
2929 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002930 // This test creates an implicit cast from int to char.
2931 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002932 varDecl(hasInitializer(ignoringParenImpCasts(
2933 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002934}
2935
2936TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
2937 // This test verifies that expressions that do not have parentheses or
2938 // implicit casts still match.
2939 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002940 varDecl(hasInitializer(ignoringParenImpCasts(
2941 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002942 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002943 varDecl(hasInitializer(ignoringParenImpCasts(
2944 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002945}
2946
2947TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
2948 // These tests verify that ignoringParenImpCasts does not match if
2949 // the inner matcher does not match.
2950 // This test creates an implicit cast.
2951 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002952 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002953 unless(anything()))))));
2954 // These tests verify that ignoringParenAndImplictCasts does not look
2955 // through explicit casts.
2956 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002957 varDecl(hasInitializer(ignoringParenImpCasts(
2958 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002959 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002960 varDecl(hasInitializer(ignoringParenImpCasts(
2961 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002962 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002963 varDecl(hasInitializer(ignoringParenImpCasts(
2964 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002965}
2966
Manuel Klimeke9235692012-07-25 10:02:02 +00002967TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002968 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
2969 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002970 implicitCastExpr(
2971 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002972}
2973
Manuel Klimeke9235692012-07-25 10:02:02 +00002974TEST(HasSourceExpression, MatchesExplicitCasts) {
2975 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002976 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002977 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002978 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00002979}
2980
Manuel Klimek04616e42012-07-06 05:48:52 +00002981TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002982 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002983}
2984
2985TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002986 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002987}
2988
2989TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002990 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002991}
2992
2993TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002994 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002995}
2996
Samuel Benzaquenf1066292014-04-02 13:12:14 +00002997TEST(ExprWithCleanups, MatchesExprWithCleanups) {
2998 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
2999 "const Foo f = Foo();",
3000 varDecl(hasInitializer(exprWithCleanups()))));
3001 EXPECT_FALSE(matches("struct Foo { };"
3002 "const Foo f = Foo();",
3003 varDecl(hasInitializer(exprWithCleanups()))));
3004}
3005
Daniel Jasper1dad1832012-07-10 20:20:19 +00003006TEST(InitListExpression, MatchesInitListExpression) {
3007 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3008 initListExpr(hasType(asString("int [2]")))));
3009 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003010 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003011}
3012
3013TEST(UsingDeclaration, MatchesUsingDeclarations) {
3014 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3015 usingDecl()));
3016}
3017
3018TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3019 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3020 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3021}
3022
3023TEST(UsingDeclaration, MatchesSpecificTarget) {
3024 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3025 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003026 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003027 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3028 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003029 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003030}
3031
3032TEST(UsingDeclaration, ThroughUsingDeclaration) {
3033 EXPECT_TRUE(matches(
3034 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003035 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003036 EXPECT_TRUE(notMatches(
3037 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003038 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003039}
3040
Sam Panzerd624bfb2012-08-16 17:20:59 +00003041TEST(SingleDecl, IsSingleDecl) {
3042 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003043 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003044 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3045 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3046 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3047 SingleDeclStmt));
3048}
3049
3050TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003051 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003052
3053 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003054 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003055 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003056 declStmt(containsDeclaration(0, MatchesInit),
3057 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003058 unsigned WrongIndex = 42;
3059 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003060 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003061 MatchesInit))));
3062}
3063
3064TEST(DeclCount, DeclCountIsCorrect) {
3065 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003066 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003067 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003068 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003069 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003070 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003071}
3072
Manuel Klimek04616e42012-07-06 05:48:52 +00003073TEST(While, MatchesWhileLoops) {
3074 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3075 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3076 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3077}
3078
3079TEST(Do, MatchesDoLoops) {
3080 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3081 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3082}
3083
3084TEST(Do, DoesNotMatchWhileLoops) {
3085 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3086}
3087
3088TEST(SwitchCase, MatchesCase) {
3089 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3090 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3091 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3092 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3093}
3094
Daniel Jasper87c3d362012-09-20 14:12:57 +00003095TEST(SwitchCase, MatchesSwitch) {
3096 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3097 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3098 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3099 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3100}
3101
Peter Collingbourne3154a102013-05-10 11:52:02 +00003102TEST(SwitchCase, MatchesEachCase) {
3103 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3104 switchStmt(forEachSwitchCase(caseStmt()))));
3105 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3106 switchStmt(forEachSwitchCase(caseStmt()))));
3107 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3108 switchStmt(forEachSwitchCase(caseStmt()))));
3109 EXPECT_TRUE(notMatches(
3110 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3111 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3112 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3113 switchStmt(forEachSwitchCase(
3114 caseStmt(hasCaseConstant(integerLiteral()))))));
3115 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3116 switchStmt(forEachSwitchCase(
3117 caseStmt(hasCaseConstant(integerLiteral()))))));
3118 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3119 switchStmt(forEachSwitchCase(
3120 caseStmt(hasCaseConstant(integerLiteral()))))));
3121 EXPECT_TRUE(matchAndVerifyResultTrue(
3122 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3123 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3124 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3125}
3126
Manuel Klimekba46fc02013-07-19 11:50:54 +00003127TEST(ForEachConstructorInitializer, MatchesInitializers) {
3128 EXPECT_TRUE(matches(
3129 "struct X { X() : i(42), j(42) {} int i, j; };",
3130 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3131}
3132
Daniel Jasper87c3d362012-09-20 14:12:57 +00003133TEST(ExceptionHandling, SimpleCases) {
3134 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3135 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3136 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3137 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3138 throwExpr()));
3139 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3140 throwExpr()));
3141}
3142
Manuel Klimek04616e42012-07-06 05:48:52 +00003143TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3144 EXPECT_TRUE(notMatches(
3145 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003146 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003147 EXPECT_TRUE(notMatches(
3148 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003149 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003150}
3151
3152TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3153 EXPECT_TRUE(matches(
3154 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003155 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003156}
3157
3158TEST(ForEach, BindsOneNode) {
3159 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003160 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003161 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003162}
3163
3164TEST(ForEach, BindsMultipleNodes) {
3165 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003166 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003167 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003168}
3169
3170TEST(ForEach, BindsRecursiveCombinations) {
3171 EXPECT_TRUE(matchAndVerifyResultTrue(
3172 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003173 recordDecl(hasName("C"),
3174 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003175 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003176}
3177
3178TEST(ForEachDescendant, BindsOneNode) {
3179 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003180 recordDecl(hasName("C"),
3181 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003182 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003183}
3184
Daniel Jasper94a56852012-11-16 18:39:22 +00003185TEST(ForEachDescendant, NestedForEachDescendant) {
3186 DeclarationMatcher m = recordDecl(
3187 isDefinition(), decl().bind("x"), hasName("C"));
3188 EXPECT_TRUE(matchAndVerifyResultTrue(
3189 "class A { class B { class C {}; }; };",
3190 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3191 new VerifyIdIsBoundTo<Decl>("x", "C")));
3192
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003193 // Check that a partial match of 'm' that binds 'x' in the
3194 // first part of anyOf(m, anything()) will not overwrite the
3195 // binding created by the earlier binding in the hasDescendant.
3196 EXPECT_TRUE(matchAndVerifyResultTrue(
3197 "class A { class B { class C {}; }; };",
3198 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3199 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003200}
3201
Manuel Klimek04616e42012-07-06 05:48:52 +00003202TEST(ForEachDescendant, BindsMultipleNodes) {
3203 EXPECT_TRUE(matchAndVerifyResultTrue(
3204 "class C { class D { int x; int y; }; "
3205 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003206 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003207 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003208}
3209
3210TEST(ForEachDescendant, BindsRecursiveCombinations) {
3211 EXPECT_TRUE(matchAndVerifyResultTrue(
3212 "class C { class D { "
3213 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003214 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3215 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003216 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003217}
3218
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003219TEST(ForEachDescendant, BindsCombinations) {
3220 EXPECT_TRUE(matchAndVerifyResultTrue(
3221 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3222 "(true) {} }",
3223 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3224 forEachDescendant(whileStmt().bind("while"))),
3225 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3226}
3227
3228TEST(Has, DoesNotDeleteBindings) {
3229 EXPECT_TRUE(matchAndVerifyResultTrue(
3230 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3231 new VerifyIdIsBoundTo<Decl>("x", 1)));
3232}
3233
3234TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3235 // Those matchers cover all the cases where an inner matcher is called
3236 // and there is not a 1:1 relationship between the match of the outer
3237 // matcher and the match of the inner matcher.
3238 // The pattern to look for is:
3239 // ... return InnerMatcher.matches(...); ...
3240 // In which case no special handling is needed.
3241 //
3242 // On the other hand, if there are multiple alternative matches
3243 // (for example forEach*) or matches might be discarded (for example has*)
3244 // the implementation must make sure that the discarded matches do not
3245 // affect the bindings.
3246 // When new such matchers are added, add a test here that:
3247 // - matches a simple node, and binds it as the first thing in the matcher:
3248 // recordDecl(decl().bind("x"), hasName("X")))
3249 // - uses the matcher under test afterwards in a way that not the first
3250 // alternative is matched; for anyOf, that means the first branch
3251 // would need to return false; for hasAncestor, it means that not
3252 // the direct parent matches the inner matcher.
3253
3254 EXPECT_TRUE(matchAndVerifyResultTrue(
3255 "class X { int y; };",
3256 recordDecl(
3257 recordDecl().bind("x"), hasName("::X"),
3258 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3259 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3260 EXPECT_TRUE(matchAndVerifyResultTrue(
3261 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3262 anyOf(unless(anything()), anything())),
3263 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3264 EXPECT_TRUE(matchAndVerifyResultTrue(
3265 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3266 classTemplateSpecializationDecl(
3267 decl().bind("x"),
3268 hasAnyTemplateArgument(refersToType(asString("int")))),
3269 new VerifyIdIsBoundTo<Decl>("x", 1)));
3270 EXPECT_TRUE(matchAndVerifyResultTrue(
3271 "class X { void f(); void g(); };",
3272 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3273 new VerifyIdIsBoundTo<Decl>("x", 1)));
3274 EXPECT_TRUE(matchAndVerifyResultTrue(
3275 "class X { X() : a(1), b(2) {} double a; int b; };",
3276 recordDecl(decl().bind("x"),
3277 has(constructorDecl(
3278 hasAnyConstructorInitializer(forField(hasName("b")))))),
3279 new VerifyIdIsBoundTo<Decl>("x", 1)));
3280 EXPECT_TRUE(matchAndVerifyResultTrue(
3281 "void x(int, int) { x(0, 42); }",
3282 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3283 new VerifyIdIsBoundTo<Expr>("x", 1)));
3284 EXPECT_TRUE(matchAndVerifyResultTrue(
3285 "void x(int, int y) {}",
3286 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3287 new VerifyIdIsBoundTo<Decl>("x", 1)));
3288 EXPECT_TRUE(matchAndVerifyResultTrue(
3289 "void x() { return; if (true) {} }",
3290 functionDecl(decl().bind("x"),
3291 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3292 new VerifyIdIsBoundTo<Decl>("x", 1)));
3293 EXPECT_TRUE(matchAndVerifyResultTrue(
3294 "namespace X { void b(int); void b(); }"
3295 "using X::b;",
3296 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3297 functionDecl(parameterCountIs(1))))),
3298 new VerifyIdIsBoundTo<Decl>("x", 1)));
3299 EXPECT_TRUE(matchAndVerifyResultTrue(
3300 "class A{}; class B{}; class C : B, A {};",
3301 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3302 new VerifyIdIsBoundTo<Decl>("x", 1)));
3303 EXPECT_TRUE(matchAndVerifyResultTrue(
3304 "class A{}; typedef A B; typedef A C; typedef A D;"
3305 "class E : A {};",
3306 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3307 new VerifyIdIsBoundTo<Decl>("x", 1)));
3308 EXPECT_TRUE(matchAndVerifyResultTrue(
3309 "class A { class B { void f() {} }; };",
3310 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3311 new VerifyIdIsBoundTo<Decl>("x", 1)));
3312 EXPECT_TRUE(matchAndVerifyResultTrue(
3313 "template <typename T> struct A { struct B {"
3314 " void f() { if(true) {} }"
3315 "}; };"
3316 "void t() { A<int>::B b; b.f(); }",
3317 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3318 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3319 EXPECT_TRUE(matchAndVerifyResultTrue(
3320 "class A {};",
3321 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3322 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003323 EXPECT_TRUE(matchAndVerifyResultTrue(
3324 "class A { A() : s(), i(42) {} const char *s; int i; };",
3325 constructorDecl(hasName("::A::A"), decl().bind("x"),
3326 forEachConstructorInitializer(forField(hasName("i")))),
3327 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003328}
3329
Daniel Jasper33806cd2012-11-11 22:14:55 +00003330TEST(ForEachDescendant, BindsCorrectNodes) {
3331 EXPECT_TRUE(matchAndVerifyResultTrue(
3332 "class C { void f(); int i; };",
3333 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3334 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3335 EXPECT_TRUE(matchAndVerifyResultTrue(
3336 "class C { void f() {} int i; };",
3337 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3338 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3339}
3340
Manuel Klimekabf43712013-02-04 10:59:20 +00003341TEST(FindAll, BindsNodeOnMatch) {
3342 EXPECT_TRUE(matchAndVerifyResultTrue(
3343 "class A {};",
3344 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3345 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3346}
3347
3348TEST(FindAll, BindsDescendantNodeOnMatch) {
3349 EXPECT_TRUE(matchAndVerifyResultTrue(
3350 "class A { int a; int b; };",
3351 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3352 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3353}
3354
3355TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3356 EXPECT_TRUE(matchAndVerifyResultTrue(
3357 "class A { int a; int b; };",
3358 recordDecl(hasName("::A"),
3359 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3360 fieldDecl().bind("v"))))),
3361 new VerifyIdIsBoundTo<Decl>("v", 3)));
3362
3363 EXPECT_TRUE(matchAndVerifyResultTrue(
3364 "class A { class B {}; class C {}; };",
3365 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3366 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3367}
3368
Manuel Klimek88b95872013-02-04 09:42:38 +00003369TEST(EachOf, TriggersForEachMatch) {
3370 EXPECT_TRUE(matchAndVerifyResultTrue(
3371 "class A { int a; int b; };",
3372 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3373 has(fieldDecl(hasName("b")).bind("v")))),
3374 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3375}
3376
3377TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3378 EXPECT_TRUE(matchAndVerifyResultTrue(
3379 "class A { int a; int c; };",
3380 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3381 has(fieldDecl(hasName("b")).bind("v")))),
3382 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3383 EXPECT_TRUE(matchAndVerifyResultTrue(
3384 "class A { int c; int b; };",
3385 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3386 has(fieldDecl(hasName("b")).bind("v")))),
3387 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3388 EXPECT_TRUE(notMatches(
3389 "class A { int c; int d; };",
3390 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3391 has(fieldDecl(hasName("b")).bind("v"))))));
3392}
Manuel Klimek04616e42012-07-06 05:48:52 +00003393
3394TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3395 // Make sure that we can both match the class by name (::X) and by the type
3396 // the template was instantiated with (via a field).
3397
3398 EXPECT_TRUE(matches(
3399 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003400 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003401
3402 EXPECT_TRUE(matches(
3403 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003404 recordDecl(isTemplateInstantiation(), hasDescendant(
3405 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003406}
3407
3408TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3409 EXPECT_TRUE(matches(
3410 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003411 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003412 isTemplateInstantiation())));
3413}
3414
3415TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3416 EXPECT_TRUE(matches(
3417 "template <typename T> class X { T t; }; class A {};"
3418 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003419 recordDecl(isTemplateInstantiation(), hasDescendant(
3420 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003421}
3422
3423TEST(IsTemplateInstantiation,
3424 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3425 EXPECT_TRUE(matches(
3426 "template <typename T> class X {};"
3427 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003428 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003429}
3430
3431TEST(IsTemplateInstantiation,
3432 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3433 EXPECT_TRUE(matches(
3434 "class A {};"
3435 "class X {"
3436 " template <typename U> class Y { U u; };"
3437 " Y<A> y;"
3438 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003439 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003440}
3441
3442TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3443 // FIXME: Figure out whether this makes sense. It doesn't affect the
3444 // normal use case as long as the uppermost instantiation always is marked
3445 // as template instantiation, but it might be confusing as a predicate.
3446 EXPECT_TRUE(matches(
3447 "class A {};"
3448 "template <typename T> class X {"
3449 " template <typename U> class Y { U u; };"
3450 " Y<T> y;"
3451 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003452 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003453}
3454
3455TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3456 EXPECT_TRUE(notMatches(
3457 "template <typename T> class X {}; class A {};"
3458 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003459 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003460}
3461
3462TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3463 EXPECT_TRUE(notMatches(
3464 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003465 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003466}
3467
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003468TEST(IsExplicitTemplateSpecialization,
3469 DoesNotMatchPrimaryTemplate) {
3470 EXPECT_TRUE(notMatches(
3471 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003472 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003473 EXPECT_TRUE(notMatches(
3474 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003475 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003476}
3477
3478TEST(IsExplicitTemplateSpecialization,
3479 DoesNotMatchExplicitTemplateInstantiations) {
3480 EXPECT_TRUE(notMatches(
3481 "template <typename T> class X {};"
3482 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003483 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003484 EXPECT_TRUE(notMatches(
3485 "template <typename T> void f(T t) {}"
3486 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003487 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003488}
3489
3490TEST(IsExplicitTemplateSpecialization,
3491 DoesNotMatchImplicitTemplateInstantiations) {
3492 EXPECT_TRUE(notMatches(
3493 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003494 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003495 EXPECT_TRUE(notMatches(
3496 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003497 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003498}
3499
3500TEST(IsExplicitTemplateSpecialization,
3501 MatchesExplicitTemplateSpecializations) {
3502 EXPECT_TRUE(matches(
3503 "template <typename T> class X {};"
3504 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003505 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003506 EXPECT_TRUE(matches(
3507 "template <typename T> void f(T t) {}"
3508 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003509 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003510}
3511
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003512TEST(HasAncenstor, MatchesDeclarationAncestors) {
3513 EXPECT_TRUE(matches(
3514 "class A { class B { class C {}; }; };",
3515 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3516}
3517
3518TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3519 EXPECT_TRUE(notMatches(
3520 "class A { class B { class C {}; }; };",
3521 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3522}
3523
3524TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3525 EXPECT_TRUE(matches(
3526 "class A { class B { void f() { C c; } class C {}; }; };",
3527 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3528 hasAncestor(recordDecl(hasName("A"))))))));
3529}
3530
3531TEST(HasAncenstor, MatchesStatementAncestors) {
3532 EXPECT_TRUE(matches(
3533 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003534 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003535}
3536
3537TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3538 EXPECT_TRUE(matches(
3539 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003540 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003541}
3542
3543TEST(HasAncestor, BindsRecursiveCombinations) {
3544 EXPECT_TRUE(matchAndVerifyResultTrue(
3545 "class C { class D { class E { class F { int y; }; }; }; };",
3546 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003547 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003548}
3549
3550TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3551 EXPECT_TRUE(matchAndVerifyResultTrue(
3552 "class C { class D { class E { class F { int y; }; }; }; };",
3553 fieldDecl(hasAncestor(
3554 decl(
3555 hasDescendant(recordDecl(isDefinition(),
3556 hasAncestor(recordDecl())))
3557 ).bind("d")
3558 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003559 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003560}
3561
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003562TEST(HasAncestor, MatchesClosestAncestor) {
3563 EXPECT_TRUE(matchAndVerifyResultTrue(
3564 "template <typename T> struct C {"
3565 " void f(int) {"
3566 " struct I { void g(T) { int x; } } i; i.g(42);"
3567 " }"
3568 "};"
3569 "template struct C<int>;",
3570 varDecl(hasName("x"),
3571 hasAncestor(functionDecl(hasParameter(
3572 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3573 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3574}
3575
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003576TEST(HasAncestor, MatchesInTemplateInstantiations) {
3577 EXPECT_TRUE(matches(
3578 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3579 "A<int>::B::C a;",
3580 fieldDecl(hasType(asString("int")),
3581 hasAncestor(recordDecl(hasName("A"))))));
3582}
3583
3584TEST(HasAncestor, MatchesInImplicitCode) {
3585 EXPECT_TRUE(matches(
3586 "struct X {}; struct A { A() {} X x; };",
3587 constructorDecl(
3588 hasAnyConstructorInitializer(withInitializer(expr(
3589 hasAncestor(recordDecl(hasName("A")))))))));
3590}
3591
Daniel Jasper632aea92012-10-22 16:26:51 +00003592TEST(HasParent, MatchesOnlyParent) {
3593 EXPECT_TRUE(matches(
3594 "void f() { if (true) { int x = 42; } }",
3595 compoundStmt(hasParent(ifStmt()))));
3596 EXPECT_TRUE(notMatches(
3597 "void f() { for (;;) { int x = 42; } }",
3598 compoundStmt(hasParent(ifStmt()))));
3599 EXPECT_TRUE(notMatches(
3600 "void f() { if (true) for (;;) { int x = 42; } }",
3601 compoundStmt(hasParent(ifStmt()))));
3602}
3603
Manuel Klimekc844a462012-12-06 14:42:48 +00003604TEST(HasAncestor, MatchesAllAncestors) {
3605 EXPECT_TRUE(matches(
3606 "template <typename T> struct C { static void f() { 42; } };"
3607 "void t() { C<int>::f(); }",
3608 integerLiteral(
3609 equals(42),
3610 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3611 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3612}
3613
3614TEST(HasParent, MatchesAllParents) {
3615 EXPECT_TRUE(matches(
3616 "template <typename T> struct C { static void f() { 42; } };"
3617 "void t() { C<int>::f(); }",
3618 integerLiteral(
3619 equals(42),
3620 hasParent(compoundStmt(hasParent(functionDecl(
3621 hasParent(recordDecl(isTemplateInstantiation())))))))));
3622 EXPECT_TRUE(matches(
3623 "template <typename T> struct C { static void f() { 42; } };"
3624 "void t() { C<int>::f(); }",
3625 integerLiteral(
3626 equals(42),
3627 hasParent(compoundStmt(hasParent(functionDecl(
3628 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3629 EXPECT_TRUE(matches(
3630 "template <typename T> struct C { static void f() { 42; } };"
3631 "void t() { C<int>::f(); }",
3632 integerLiteral(equals(42),
3633 hasParent(compoundStmt(allOf(
3634 hasParent(functionDecl(
3635 hasParent(recordDecl(isTemplateInstantiation())))),
3636 hasParent(functionDecl(hasParent(recordDecl(
3637 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003638 EXPECT_TRUE(
3639 notMatches("template <typename T> struct C { static void f() {} };"
3640 "void t() { C<int>::f(); }",
3641 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003642}
3643
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003644TEST(HasParent, NoDuplicateParents) {
3645 class HasDuplicateParents : public BoundNodesCallback {
3646 public:
3647 bool run(const BoundNodes *Nodes) override { return false; }
3648 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3649 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3650 std::set<const void *> Parents;
3651 for (const auto &Parent : Context->getParents(*Node)) {
3652 if (!Parents.insert(Parent.getMemoizationData()).second) {
3653 return true;
3654 }
3655 }
3656 return false;
3657 }
3658 };
3659 EXPECT_FALSE(matchAndVerifyResultTrue(
3660 "template <typename T> int Foo() { return 1 + 2; }\n"
3661 "int x = Foo<int>() + Foo<unsigned>();",
3662 stmt().bind("node"), new HasDuplicateParents()));
3663}
3664
Daniel Jasper516b02e2012-10-17 08:52:59 +00003665TEST(TypeMatching, MatchesTypes) {
3666 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3667}
3668
3669TEST(TypeMatching, MatchesArrayTypes) {
3670 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3671 EXPECT_TRUE(matches("int a[42];", arrayType()));
3672 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3673
3674 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3675 arrayType(hasElementType(builtinType()))));
3676
3677 EXPECT_TRUE(matches(
3678 "int const a[] = { 2, 3 };",
3679 qualType(arrayType(hasElementType(builtinType())))));
3680 EXPECT_TRUE(matches(
3681 "int const a[] = { 2, 3 };",
3682 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3683 EXPECT_TRUE(matches(
3684 "typedef const int T; T x[] = { 1, 2 };",
3685 qualType(isConstQualified(), arrayType())));
3686
3687 EXPECT_TRUE(notMatches(
3688 "int a[] = { 2, 3 };",
3689 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3690 EXPECT_TRUE(notMatches(
3691 "int a[] = { 2, 3 };",
3692 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3693 EXPECT_TRUE(notMatches(
3694 "int const a[] = { 2, 3 };",
3695 qualType(arrayType(hasElementType(builtinType())),
3696 unless(isConstQualified()))));
3697
3698 EXPECT_TRUE(matches("int a[2];",
3699 constantArrayType(hasElementType(builtinType()))));
3700 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3701}
3702
3703TEST(TypeMatching, MatchesComplexTypes) {
3704 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3705 EXPECT_TRUE(matches(
3706 "_Complex float f;",
3707 complexType(hasElementType(builtinType()))));
3708 EXPECT_TRUE(notMatches(
3709 "_Complex float f;",
3710 complexType(hasElementType(isInteger()))));
3711}
3712
3713TEST(TypeMatching, MatchesConstantArrayTypes) {
3714 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3715 EXPECT_TRUE(notMatches(
3716 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3717 constantArrayType(hasElementType(builtinType()))));
3718
3719 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3720 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3721 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3722}
3723
3724TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3725 EXPECT_TRUE(matches(
3726 "template <typename T, int Size> class array { T data[Size]; };",
3727 dependentSizedArrayType()));
3728 EXPECT_TRUE(notMatches(
3729 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3730 dependentSizedArrayType()));
3731}
3732
3733TEST(TypeMatching, MatchesIncompleteArrayType) {
3734 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3735 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3736
3737 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3738 incompleteArrayType()));
3739}
3740
3741TEST(TypeMatching, MatchesVariableArrayType) {
3742 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3743 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3744
3745 EXPECT_TRUE(matches(
3746 "void f(int b) { int a[b]; }",
3747 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3748 varDecl(hasName("b")))))))));
3749}
3750
3751TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003752 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3753 llvm::Triple::Win32) {
3754 // FIXME: Make this work for MSVC.
3755 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003756
David Majnemer197e2102014-03-05 06:32:38 +00003757 EXPECT_TRUE(matches("_Atomic(int) i;",
3758 atomicType(hasValueType(isInteger()))));
3759 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3760 atomicType(hasValueType(isInteger()))));
3761 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003762}
3763
3764TEST(TypeMatching, MatchesAutoTypes) {
3765 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3766 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3767 autoType()));
3768
Richard Smith061f1e22013-04-30 21:23:01 +00003769 // FIXME: Matching against the type-as-written can't work here, because the
3770 // type as written was not deduced.
3771 //EXPECT_TRUE(matches("auto a = 1;",
3772 // autoType(hasDeducedType(isInteger()))));
3773 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3774 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003775}
3776
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00003777TEST(TypeMatching, MatchesFunctionTypes) {
3778 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3779 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3780}
3781
Edwin Vaneec074802013-04-01 18:33:34 +00003782TEST(TypeMatching, MatchesParenType) {
3783 EXPECT_TRUE(
3784 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3785 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3786
3787 EXPECT_TRUE(matches(
3788 "int (*ptr_to_func)(int);",
3789 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3790 EXPECT_TRUE(notMatches(
3791 "int (*ptr_to_array)[4];",
3792 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3793}
3794
Daniel Jasper516b02e2012-10-17 08:52:59 +00003795TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003796 // FIXME: Reactive when these tests can be more specific (not matching
3797 // implicit code on certain platforms), likely when we have hasDescendant for
3798 // Types/TypeLocs.
3799 //EXPECT_TRUE(matchAndVerifyResultTrue(
3800 // "int* a;",
3801 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3802 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3803 //EXPECT_TRUE(matchAndVerifyResultTrue(
3804 // "int* a;",
3805 // pointerTypeLoc().bind("loc"),
3806 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003807 EXPECT_TRUE(matches(
3808 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003809 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003810 EXPECT_TRUE(matches(
3811 "int** a;",
3812 loc(pointerType(pointee(pointerType())))));
3813 EXPECT_TRUE(matches(
3814 "int* b; int* * const a = &b;",
3815 loc(qualType(isConstQualified(), pointerType()))));
3816
3817 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00003818 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3819 hasType(blockPointerType()))));
3820 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3821 hasType(memberPointerType()))));
3822 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3823 hasType(pointerType()))));
3824 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3825 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003826 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3827 hasType(lValueReferenceType()))));
3828 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3829 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003830
Daniel Jasper7943eb52012-10-17 13:35:36 +00003831 Fragment = "int *ptr;";
3832 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3833 hasType(blockPointerType()))));
3834 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3835 hasType(memberPointerType()))));
3836 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3837 hasType(pointerType()))));
3838 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3839 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003840
Daniel Jasper7943eb52012-10-17 13:35:36 +00003841 Fragment = "int a; int &ref = a;";
3842 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3843 hasType(blockPointerType()))));
3844 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3845 hasType(memberPointerType()))));
3846 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3847 hasType(pointerType()))));
3848 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3849 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003850 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3851 hasType(lValueReferenceType()))));
3852 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3853 hasType(rValueReferenceType()))));
3854
3855 Fragment = "int &&ref = 2;";
3856 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3857 hasType(blockPointerType()))));
3858 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3859 hasType(memberPointerType()))));
3860 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3861 hasType(pointerType()))));
3862 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3863 hasType(referenceType()))));
3864 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3865 hasType(lValueReferenceType()))));
3866 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3867 hasType(rValueReferenceType()))));
3868}
3869
3870TEST(TypeMatching, AutoRefTypes) {
3871 std::string Fragment = "auto a = 1;"
3872 "auto b = a;"
3873 "auto &c = a;"
3874 "auto &&d = c;"
3875 "auto &&e = 2;";
3876 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
3877 hasType(referenceType()))));
3878 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
3879 hasType(referenceType()))));
3880 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3881 hasType(referenceType()))));
3882 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3883 hasType(lValueReferenceType()))));
3884 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
3885 hasType(rValueReferenceType()))));
3886 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3887 hasType(referenceType()))));
3888 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3889 hasType(lValueReferenceType()))));
3890 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
3891 hasType(rValueReferenceType()))));
3892 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3893 hasType(referenceType()))));
3894 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
3895 hasType(lValueReferenceType()))));
3896 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3897 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003898}
3899
3900TEST(TypeMatching, PointeeTypes) {
3901 EXPECT_TRUE(matches("int b; int &a = b;",
3902 referenceType(pointee(builtinType()))));
3903 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
3904
3905 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003906 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003907
3908 EXPECT_TRUE(matches(
3909 "int const *A;",
3910 pointerType(pointee(isConstQualified(), builtinType()))));
3911 EXPECT_TRUE(notMatches(
3912 "int *A;",
3913 pointerType(pointee(isConstQualified(), builtinType()))));
3914}
3915
3916TEST(TypeMatching, MatchesPointersToConstTypes) {
3917 EXPECT_TRUE(matches("int b; int * const a = &b;",
3918 loc(pointerType())));
3919 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00003920 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003921 EXPECT_TRUE(matches(
3922 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00003923 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003924 EXPECT_TRUE(matches(
3925 "int b; const int * a = &b;",
3926 pointerType(pointee(builtinType()))));
3927}
3928
3929TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003930 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
3931 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003932}
3933
Edwin Vanef901b712013-02-25 14:49:29 +00003934TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00003935 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00003936 templateSpecializationType()));
3937}
3938
Edwin Vaneb6eae142013-02-25 20:43:32 +00003939TEST(TypeMatching, MatchesRecordType) {
3940 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00003941 EXPECT_TRUE(matches("struct S{}; S s;",
3942 recordType(hasDeclaration(recordDecl(hasName("S"))))));
3943 EXPECT_TRUE(notMatches("int i;",
3944 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00003945}
3946
3947TEST(TypeMatching, MatchesElaboratedType) {
3948 EXPECT_TRUE(matches(
3949 "namespace N {"
3950 " namespace M {"
3951 " class D {};"
3952 " }"
3953 "}"
3954 "N::M::D d;", elaboratedType()));
3955 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
3956 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
3957}
3958
3959TEST(ElaboratedTypeNarrowing, hasQualifier) {
3960 EXPECT_TRUE(matches(
3961 "namespace N {"
3962 " namespace M {"
3963 " class D {};"
3964 " }"
3965 "}"
3966 "N::M::D d;",
3967 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
3968 EXPECT_TRUE(notMatches(
3969 "namespace M {"
3970 " class D {};"
3971 "}"
3972 "M::D d;",
3973 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00003974 EXPECT_TRUE(notMatches(
3975 "struct D {"
3976 "} d;",
3977 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00003978}
3979
3980TEST(ElaboratedTypeNarrowing, namesType) {
3981 EXPECT_TRUE(matches(
3982 "namespace N {"
3983 " namespace M {"
3984 " class D {};"
3985 " }"
3986 "}"
3987 "N::M::D d;",
3988 elaboratedType(elaboratedType(namesType(recordType(
3989 hasDeclaration(namedDecl(hasName("D")))))))));
3990 EXPECT_TRUE(notMatches(
3991 "namespace M {"
3992 " class D {};"
3993 "}"
3994 "M::D d;",
3995 elaboratedType(elaboratedType(namesType(typedefType())))));
3996}
3997
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003998TEST(NNS, MatchesNestedNameSpecifiers) {
3999 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4000 nestedNameSpecifier()));
4001 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4002 nestedNameSpecifier()));
4003 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4004 nestedNameSpecifier()));
4005
4006 EXPECT_TRUE(matches(
4007 "struct A { static void f() {} }; void g() { A::f(); }",
4008 nestedNameSpecifier()));
4009 EXPECT_TRUE(notMatches(
4010 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4011 nestedNameSpecifier()));
4012}
4013
Daniel Jasper87c3d362012-09-20 14:12:57 +00004014TEST(NullStatement, SimpleCases) {
4015 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4016 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4017}
4018
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004019TEST(NNS, MatchesTypes) {
4020 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4021 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4022 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4023 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4024 Matcher));
4025 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4026}
4027
4028TEST(NNS, MatchesNamespaceDecls) {
4029 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4030 specifiesNamespace(hasName("ns")));
4031 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4032 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4033 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4034}
4035
4036TEST(NNS, BindsNestedNameSpecifiers) {
4037 EXPECT_TRUE(matchAndVerifyResultTrue(
4038 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4039 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4040 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4041}
4042
4043TEST(NNS, BindsNestedNameSpecifierLocs) {
4044 EXPECT_TRUE(matchAndVerifyResultTrue(
4045 "namespace ns { struct B {}; } ns::B b;",
4046 loc(nestedNameSpecifier()).bind("loc"),
4047 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4048}
4049
4050TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4051 EXPECT_TRUE(matches(
4052 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4053 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4054 EXPECT_TRUE(matches(
4055 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004056 nestedNameSpecifierLoc(hasPrefix(
4057 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004058}
4059
Daniel Jasper6fc34332012-10-30 15:42:00 +00004060TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4061 std::string Fragment =
4062 "namespace a { struct A { struct B { struct C {}; }; }; };"
4063 "void f() { a::A::B::C c; }";
4064 EXPECT_TRUE(matches(
4065 Fragment,
4066 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4067 hasDescendant(nestedNameSpecifier(
4068 specifiesNamespace(hasName("a")))))));
4069 EXPECT_TRUE(notMatches(
4070 Fragment,
4071 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4072 has(nestedNameSpecifier(
4073 specifiesNamespace(hasName("a")))))));
4074 EXPECT_TRUE(matches(
4075 Fragment,
4076 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4077 has(nestedNameSpecifier(
4078 specifiesNamespace(hasName("a")))))));
4079
4080 // Not really useful because a NestedNameSpecifier can af at most one child,
4081 // but to complete the interface.
4082 EXPECT_TRUE(matchAndVerifyResultTrue(
4083 Fragment,
4084 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4085 forEach(nestedNameSpecifier().bind("x"))),
4086 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4087}
4088
4089TEST(NNS, NestedNameSpecifiersAsDescendants) {
4090 std::string Fragment =
4091 "namespace a { struct A { struct B { struct C {}; }; }; };"
4092 "void f() { a::A::B::C c; }";
4093 EXPECT_TRUE(matches(
4094 Fragment,
4095 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4096 asString("struct a::A")))))));
4097 EXPECT_TRUE(matchAndVerifyResultTrue(
4098 Fragment,
4099 functionDecl(hasName("f"),
4100 forEachDescendant(nestedNameSpecifier().bind("x"))),
4101 // Nested names: a, a::A and a::A::B.
4102 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4103}
4104
4105TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4106 std::string Fragment =
4107 "namespace a { struct A { struct B { struct C {}; }; }; };"
4108 "void f() { a::A::B::C c; }";
4109 EXPECT_TRUE(matches(
4110 Fragment,
4111 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4112 hasDescendant(loc(nestedNameSpecifier(
4113 specifiesNamespace(hasName("a"))))))));
4114 EXPECT_TRUE(notMatches(
4115 Fragment,
4116 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4117 has(loc(nestedNameSpecifier(
4118 specifiesNamespace(hasName("a"))))))));
4119 EXPECT_TRUE(matches(
4120 Fragment,
4121 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4122 has(loc(nestedNameSpecifier(
4123 specifiesNamespace(hasName("a"))))))));
4124
4125 EXPECT_TRUE(matchAndVerifyResultTrue(
4126 Fragment,
4127 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4128 forEach(nestedNameSpecifierLoc().bind("x"))),
4129 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4130}
4131
4132TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4133 std::string Fragment =
4134 "namespace a { struct A { struct B { struct C {}; }; }; };"
4135 "void f() { a::A::B::C c; }";
4136 EXPECT_TRUE(matches(
4137 Fragment,
4138 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4139 asString("struct a::A"))))))));
4140 EXPECT_TRUE(matchAndVerifyResultTrue(
4141 Fragment,
4142 functionDecl(hasName("f"),
4143 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4144 // Nested names: a, a::A and a::A::B.
4145 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4146}
4147
Manuel Klimek191c0932013-02-01 13:41:35 +00004148template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004149public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004150 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4151 StringRef InnerId)
4152 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004153 }
4154
Manuel Klimek191c0932013-02-01 13:41:35 +00004155 virtual bool run(const BoundNodes *Nodes) { return false; }
4156
Manuel Klimekc2687452012-10-24 14:47:44 +00004157 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4158 const T *Node = Nodes->getNodeAs<T>(Id);
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004159 return selectFirst<const T>(InnerId,
Craig Topper416fa342014-06-08 08:38:12 +00004160 match(InnerMatcher, *Node, *Context)) !=nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004161 }
4162private:
4163 std::string Id;
4164 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004165 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004166};
4167
4168TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004169 EXPECT_TRUE(matchAndVerifyResultTrue(
4170 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4171 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004172 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4173 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004174 EXPECT_TRUE(matchAndVerifyResultFalse(
4175 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4176 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004177 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4178 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004179}
4180
4181TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004182 EXPECT_TRUE(matchAndVerifyResultTrue(
4183 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004184 new VerifyMatchOnNode<clang::Stmt>(
4185 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004186 EXPECT_TRUE(matchAndVerifyResultFalse(
4187 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004188 new VerifyMatchOnNode<clang::Stmt>(
4189 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004190}
4191
4192TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4193 EXPECT_TRUE(matchAndVerifyResultTrue(
4194 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4195 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004196 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004197 EXPECT_TRUE(matchAndVerifyResultFalse(
4198 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4199 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004200 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004201}
4202
Manuel Klimekbee08572013-02-07 12:42:10 +00004203template <typename T>
4204class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4205public:
4206 virtual bool run(const BoundNodes *Nodes) { return false; }
4207
4208 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4209 const T *Node = Nodes->getNodeAs<T>("");
4210 return verify(*Nodes, *Context, Node);
4211 }
4212
4213 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004214 // Use the original typed pointer to verify we can pass pointers to subtypes
4215 // to equalsNode.
4216 const T *TypedNode = cast<T>(Node);
Manuel Klimekbee08572013-02-07 12:42:10 +00004217 return selectFirst<const T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004218 "", match(stmt(hasParent(
4219 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004220 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004221 }
4222 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004223 // Use the original typed pointer to verify we can pass pointers to subtypes
4224 // to equalsNode.
4225 const T *TypedNode = cast<T>(Node);
Manuel Klimekbee08572013-02-07 12:42:10 +00004226 return selectFirst<const T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004227 "", match(decl(hasParent(
4228 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004229 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004230 }
4231};
4232
4233TEST(IsEqualTo, MatchesNodesByIdentity) {
4234 EXPECT_TRUE(matchAndVerifyResultTrue(
4235 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004236 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4237 EXPECT_TRUE(matchAndVerifyResultTrue(
4238 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4239 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004240}
4241
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004242class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4243public:
4244 VerifyStartOfTranslationUnit() : Called(false) {}
4245 virtual void run(const MatchFinder::MatchResult &Result) {
4246 EXPECT_TRUE(Called);
4247 }
4248 virtual void onStartOfTranslationUnit() {
4249 Called = true;
4250 }
4251 bool Called;
4252};
4253
4254TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4255 MatchFinder Finder;
4256 VerifyStartOfTranslationUnit VerifyCallback;
4257 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004258 std::unique_ptr<FrontendActionFactory> Factory(
4259 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004260 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4261 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004262
4263 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004264 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004265 ASSERT_TRUE(AST.get());
4266 Finder.matchAST(AST->getASTContext());
4267 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004268}
4269
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004270class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4271public:
4272 VerifyEndOfTranslationUnit() : Called(false) {}
4273 virtual void run(const MatchFinder::MatchResult &Result) {
4274 EXPECT_FALSE(Called);
4275 }
4276 virtual void onEndOfTranslationUnit() {
4277 Called = true;
4278 }
4279 bool Called;
4280};
4281
4282TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4283 MatchFinder Finder;
4284 VerifyEndOfTranslationUnit VerifyCallback;
4285 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004286 std::unique_ptr<FrontendActionFactory> Factory(
4287 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004288 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4289 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004290
4291 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004292 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004293 ASSERT_TRUE(AST.get());
4294 Finder.matchAST(AST->getASTContext());
4295 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004296}
4297
Manuel Klimekbbb75852013-06-20 14:06:32 +00004298TEST(EqualsBoundNodeMatcher, QualType) {
4299 EXPECT_TRUE(matches(
4300 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4301 hasInitializer(ignoringParenImpCasts(
4302 hasType(qualType(equalsBoundNode("type"))))))));
4303 EXPECT_TRUE(notMatches("int i = 1.f;",
4304 varDecl(hasType(qualType().bind("type")),
4305 hasInitializer(ignoringParenImpCasts(hasType(
4306 qualType(equalsBoundNode("type"))))))));
4307}
4308
4309TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4310 EXPECT_TRUE(notMatches(
4311 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4312 hasInitializer(ignoringParenImpCasts(
4313 hasType(qualType(equalsBoundNode("type"))))))));
4314}
4315
4316TEST(EqualsBoundNodeMatcher, Stmt) {
4317 EXPECT_TRUE(
4318 matches("void f() { if(true) {} }",
4319 stmt(allOf(ifStmt().bind("if"),
4320 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4321
4322 EXPECT_TRUE(notMatches(
4323 "void f() { if(true) { if (true) {} } }",
4324 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4325}
4326
4327TEST(EqualsBoundNodeMatcher, Decl) {
4328 EXPECT_TRUE(matches(
4329 "class X { class Y {}; };",
4330 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4331 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4332
4333 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4334 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4335 has(decl(equalsBoundNode("record")))))));
4336}
4337
4338TEST(EqualsBoundNodeMatcher, Type) {
4339 EXPECT_TRUE(matches(
4340 "class X { int a; int b; };",
4341 recordDecl(
4342 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4343 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4344
4345 EXPECT_TRUE(notMatches(
4346 "class X { int a; double b; };",
4347 recordDecl(
4348 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4349 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4350}
4351
4352TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004353 EXPECT_TRUE(matchAndVerifyResultTrue(
4354 "int f() {"
4355 " if (1) {"
4356 " int i = 9;"
4357 " }"
4358 " int j = 10;"
4359 " {"
4360 " float k = 9.0;"
4361 " }"
4362 " return 0;"
4363 "}",
4364 // Look for variable declarations within functions whose type is the same
4365 // as the function return type.
4366 functionDecl(returns(qualType().bind("type")),
4367 forEachDescendant(varDecl(hasType(
4368 qualType(equalsBoundNode("type")))).bind("decl"))),
4369 // Only i and j should match, not k.
4370 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4371}
4372
4373TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4374 EXPECT_TRUE(matchAndVerifyResultTrue(
4375 "void f() {"
4376 " int x;"
4377 " double d;"
4378 " x = d + x - d + x;"
4379 "}",
4380 functionDecl(
4381 hasName("f"), forEachDescendant(varDecl().bind("d")),
4382 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4383 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4384}
4385
Manuel Klimekce68f772014-03-25 14:39:26 +00004386TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4387 EXPECT_TRUE(matchAndVerifyResultTrue(
4388 "struct StringRef { int size() const; const char* data() const; };"
4389 "void f(StringRef v) {"
4390 " v.data();"
4391 "}",
4392 memberCallExpr(
4393 callee(methodDecl(hasName("data"))),
4394 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4395 .bind("var")))),
4396 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4397 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4398 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4399 .bind("data"),
4400 new VerifyIdIsBoundTo<Expr>("data", 1)));
4401
4402 EXPECT_FALSE(matches(
4403 "struct StringRef { int size() const; const char* data() const; };"
4404 "void f(StringRef v) {"
4405 " v.data();"
4406 " v.size();"
4407 "}",
4408 memberCallExpr(
4409 callee(methodDecl(hasName("data"))),
4410 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4411 .bind("var")))),
4412 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4413 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4414 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4415 .bind("data")));
4416}
4417
Manuel Klimek04616e42012-07-06 05:48:52 +00004418} // end namespace ast_matchers
4419} // end namespace clang