blob: e769e887bd1b993f8ff61f20acccb91e73e704b0 [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 Jasper3dfa09b2014-07-23 13:17:47 +0000646TEST(DeclarationMatcher, HasDescendantMemoization) {
647 DeclarationMatcher CannotMemoize =
648 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
649 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
650}
651
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000652// Implements a run method that returns whether BoundNodes contains a
653// Decl bound to Id that can be dynamically cast to T.
654// Optionally checks that the check succeeded a specific number of times.
655template <typename T>
656class VerifyIdIsBoundTo : public BoundNodesCallback {
657public:
658 // Create an object that checks that a node of type \c T was bound to \c Id.
659 // Does not check for a certain number of matches.
660 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
661 : Id(Id), ExpectedCount(-1), Count(0) {}
662
663 // Create an object that checks that a node of type \c T was bound to \c Id.
664 // Checks that there were exactly \c ExpectedCount matches.
665 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
666 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
667
668 // Create an object that checks that a node of type \c T was bound to \c Id.
669 // Checks that there was exactly one match with the name \c ExpectedName.
670 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000671 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
672 int ExpectedCount = 1)
673 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
674 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000675
Craig Toppera798a9d2014-03-02 09:32:10 +0000676 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000677 if (ExpectedCount != -1)
678 EXPECT_EQ(ExpectedCount, Count);
679 if (!ExpectedName.empty())
680 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000681 Count = 0;
682 Name.clear();
683 }
684
685 ~VerifyIdIsBoundTo() {
686 EXPECT_EQ(0, Count);
687 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000688 }
689
690 virtual bool run(const BoundNodes *Nodes) {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000691 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000692 if (Nodes->getNodeAs<T>(Id)) {
693 ++Count;
694 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
695 Name = Named->getNameAsString();
696 } else if (const NestedNameSpecifier *NNS =
697 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
698 llvm::raw_string_ostream OS(Name);
699 NNS->print(OS, PrintingPolicy(LangOptions()));
700 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000701 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
702 EXPECT_NE(M.end(), I);
703 if (I != M.end())
704 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000705 return true;
706 }
Craig Topper416fa342014-06-08 08:38:12 +0000707 EXPECT_TRUE(M.count(Id) == 0 ||
708 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000709 return false;
710 }
711
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000712 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
713 return run(Nodes);
714 }
715
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000716private:
717 const std::string Id;
718 const int ExpectedCount;
719 int Count;
720 const std::string ExpectedName;
721 std::string Name;
722};
723
724TEST(HasDescendant, MatchesDescendantTypes) {
725 EXPECT_TRUE(matches("void f() { int i = 3; }",
726 decl(hasDescendant(loc(builtinType())))));
727 EXPECT_TRUE(matches("void f() { int i = 3; }",
728 stmt(hasDescendant(builtinType()))));
729
730 EXPECT_TRUE(matches("void f() { int i = 3; }",
731 stmt(hasDescendant(loc(builtinType())))));
732 EXPECT_TRUE(matches("void f() { int i = 3; }",
733 stmt(hasDescendant(qualType(builtinType())))));
734
735 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
736 stmt(hasDescendant(isInteger()))));
737
738 EXPECT_TRUE(matchAndVerifyResultTrue(
739 "void f() { int a; float c; int d; int e; }",
740 functionDecl(forEachDescendant(
741 varDecl(hasDescendant(isInteger())).bind("x"))),
742 new VerifyIdIsBoundTo<Decl>("x", 3)));
743}
744
745TEST(HasDescendant, MatchesDescendantsOfTypes) {
746 EXPECT_TRUE(matches("void f() { int*** i; }",
747 qualType(hasDescendant(builtinType()))));
748 EXPECT_TRUE(matches("void f() { int*** i; }",
749 qualType(hasDescendant(
750 pointerType(pointee(builtinType()))))));
751 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000752 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000753
754 EXPECT_TRUE(matchAndVerifyResultTrue(
755 "void f() { int*** i; }",
756 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
757 new VerifyIdIsBoundTo<Type>("x", 2)));
758}
759
760TEST(Has, MatchesChildrenOfTypes) {
761 EXPECT_TRUE(matches("int i;",
762 varDecl(hasName("i"), has(isInteger()))));
763 EXPECT_TRUE(notMatches("int** i;",
764 varDecl(hasName("i"), has(isInteger()))));
765 EXPECT_TRUE(matchAndVerifyResultTrue(
766 "int (*f)(float, int);",
767 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
768 new VerifyIdIsBoundTo<QualType>("x", 2)));
769}
770
771TEST(Has, MatchesChildTypes) {
772 EXPECT_TRUE(matches(
773 "int* i;",
774 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
775 EXPECT_TRUE(notMatches(
776 "int* i;",
777 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
778}
779
Daniel Jasper1dad1832012-07-10 20:20:19 +0000780TEST(Enum, DoesNotMatchClasses) {
781 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
782}
783
784TEST(Enum, MatchesEnums) {
785 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
786}
787
788TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000789 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000790 EXPECT_TRUE(matches("enum X{ A };", Matcher));
791 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
792 EXPECT_TRUE(notMatches("enum X {};", Matcher));
793}
794
Manuel Klimek04616e42012-07-06 05:48:52 +0000795TEST(StatementMatcher, Has) {
796 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000797 expr(hasType(pointsTo(recordDecl(hasName("X")))),
798 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000799
800 EXPECT_TRUE(matches(
801 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
802 EXPECT_TRUE(notMatches(
803 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
804}
805
806TEST(StatementMatcher, HasDescendant) {
807 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000808 expr(hasType(pointsTo(recordDecl(hasName("X")))),
809 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000810
811 EXPECT_TRUE(matches(
812 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
813 HasDescendantVariableI));
814 EXPECT_TRUE(notMatches(
815 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
816 HasDescendantVariableI));
817}
818
819TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000820 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000821
822 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
823 EXPECT_TRUE(notMatches("class A {};", TypeA));
824
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000825 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000826
827 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
828 TypeDerivedFromA));
829 EXPECT_TRUE(notMatches("class A {};", TypeA));
830
831 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000832 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000833
834 EXPECT_TRUE(
835 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
836}
837
Manuel Klimek04616e42012-07-06 05:48:52 +0000838TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000839 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000840
841 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000842 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000843
844 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000845 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000846
847 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000848 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000849
850 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
851 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000852 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000853
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000854 StatementMatcher MethodX =
855 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000856
857 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
858 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000859 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000860}
861
862TEST(Matcher, BindTheSameNameInAlternatives) {
863 StatementMatcher matcher = anyOf(
864 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000865 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000866 hasRHS(integerLiteral(equals(0)))),
867 binaryOperator(hasOperatorName("+"),
868 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000869 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000870
871 EXPECT_TRUE(matchAndVerifyResultTrue(
872 // The first branch of the matcher binds x to 0 but then fails.
873 // The second branch binds x to f() and succeeds.
874 "int f() { return 0 + f(); }",
875 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000876 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000877}
878
Manuel Klimekfdf98762012-08-30 19:41:06 +0000879TEST(Matcher, BindsIDForMemoizedResults) {
880 // Using the same matcher in two match expressions will make memoization
881 // kick in.
882 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
883 EXPECT_TRUE(matchAndVerifyResultTrue(
884 "class A { class B { class X {}; }; };",
885 DeclarationMatcher(anyOf(
886 recordDecl(hasName("A"), hasDescendant(ClassX)),
887 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000888 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000889}
890
Daniel Jasper856194d02012-12-03 15:43:25 +0000891TEST(HasDeclaration, HasDeclarationOfEnumType) {
892 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
893 expr(hasType(pointsTo(
894 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
895}
896
Edwin Vaneed936452013-02-25 14:32:42 +0000897TEST(HasDeclaration, HasGetDeclTraitTest) {
898 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
899 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
900 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
901}
902
Edwin Vane2c197e02013-02-19 17:14:34 +0000903TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
904 EXPECT_TRUE(matches("typedef int X; X a;",
905 varDecl(hasName("a"),
906 hasType(typedefType(hasDeclaration(decl()))))));
907
908 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
909}
910
Edwin Vanef901b712013-02-25 14:49:29 +0000911TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
912 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
913 varDecl(hasType(templateSpecializationType(
914 hasDeclaration(namedDecl(hasName("A"))))))));
915}
916
Manuel Klimek04616e42012-07-06 05:48:52 +0000917TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000918 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000919 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000920 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000921 EXPECT_TRUE(
922 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000923 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000924 EXPECT_TRUE(
925 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000926 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000927}
928
929TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000930 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000931 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000932 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000933 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000934 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000935 EXPECT_TRUE(
936 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000937 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000938}
939
940TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000941 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000942 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000943 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000944 EXPECT_TRUE(
945 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000946 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000947}
948
949TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000950 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000951 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000952 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000953 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000954 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000955}
956
Manuel Klimekc16c6522013-06-20 13:08:29 +0000957TEST(HasTypeLoc, MatchesDeclaratorDecls) {
958 EXPECT_TRUE(matches("int x;",
959 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
960
961 // Make sure we don't crash on implicit constructors.
962 EXPECT_TRUE(notMatches("class X {}; X x;",
963 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
964}
965
Manuel Klimek04616e42012-07-06 05:48:52 +0000966TEST(Matcher, Call) {
967 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +0000968 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000969 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000970
971 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
972 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
973
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000974 StatementMatcher MethodOnY =
975 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000976
977 EXPECT_TRUE(
978 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
979 MethodOnY));
980 EXPECT_TRUE(
981 matches("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 EXPECT_TRUE(
987 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
988 MethodOnY));
989 EXPECT_TRUE(
990 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
991 MethodOnY));
992
993 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000994 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000995
996 EXPECT_TRUE(
997 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
998 MethodOnYPointer));
999 EXPECT_TRUE(
1000 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1001 MethodOnYPointer));
1002 EXPECT_TRUE(
1003 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1004 MethodOnYPointer));
1005 EXPECT_TRUE(
1006 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1007 MethodOnYPointer));
1008 EXPECT_TRUE(
1009 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1010 MethodOnYPointer));
1011}
1012
Daniel Jasper5901e472012-10-01 13:40:41 +00001013TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001014 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001015 lambdaExpr()));
1016}
1017
1018TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001019 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1020 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001021 forRangeStmt()));
1022 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1023 forRangeStmt()));
1024}
1025
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001026TEST(Matcher, SubstNonTypeTemplateParm) {
1027 EXPECT_FALSE(matches("template<int N>\n"
1028 "struct A { static const int n = 0; };\n"
1029 "struct B : public A<42> {};",
1030 substNonTypeTemplateParmExpr()));
1031 EXPECT_TRUE(matches("template<int N>\n"
1032 "struct A { static const int n = N; };\n"
1033 "struct B : public A<42> {};",
1034 substNonTypeTemplateParmExpr()));
1035}
1036
Daniel Jasper5901e472012-10-01 13:40:41 +00001037TEST(Matcher, UserDefinedLiteral) {
1038 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1039 " return i + 1;"
1040 "}"
1041 "char c = 'a'_inc;",
1042 userDefinedLiteral()));
1043}
1044
Daniel Jasper87c3d362012-09-20 14:12:57 +00001045TEST(Matcher, FlowControl) {
1046 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1047 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1048 continueStmt()));
1049 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1050 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1051 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1052}
1053
Daniel Jasper1dad1832012-07-10 20:20:19 +00001054TEST(HasType, MatchesAsString) {
1055 EXPECT_TRUE(
1056 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001057 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001058 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001059 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001060 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001061 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001062 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001063 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001064}
1065
Manuel Klimek04616e42012-07-06 05:48:52 +00001066TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001067 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001068 // Unary operator
1069 EXPECT_TRUE(matches("class Y { }; "
1070 "bool operator!(Y x) { return false; }; "
1071 "Y y; bool c = !y;", OpCall));
1072 // No match -- special operators like "new", "delete"
1073 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1074 // we need to figure out include paths in the test.
1075 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1076 // "class Y { }; "
1077 // "void *operator new(size_t size) { return 0; } "
1078 // "Y *y = new Y;", OpCall));
1079 EXPECT_TRUE(notMatches("class Y { }; "
1080 "void operator delete(void *p) { } "
1081 "void a() {Y *y = new Y; delete y;}", OpCall));
1082 // Binary operator
1083 EXPECT_TRUE(matches("class Y { }; "
1084 "bool operator&&(Y x, Y y) { return true; }; "
1085 "Y a; Y b; bool c = a && b;",
1086 OpCall));
1087 // No match -- normal operator, not an overloaded one.
1088 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1089 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1090}
1091
1092TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1093 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001094 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001095 EXPECT_TRUE(matches("class Y { }; "
1096 "bool operator&&(Y x, Y y) { return true; }; "
1097 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1098 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001099 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001100 EXPECT_TRUE(notMatches("class Y { }; "
1101 "bool operator&&(Y x, Y y) { return true; }; "
1102 "Y a; Y b; bool c = a && b;",
1103 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001104 StatementMatcher OpStarCall =
1105 operatorCallExpr(hasOverloadedOperatorName("*"));
1106 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1107 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001108 DeclarationMatcher ClassWithOpStar =
1109 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1110 EXPECT_TRUE(matches("class Y { int operator*(); };",
1111 ClassWithOpStar));
1112 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1113 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001114 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1115 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1116 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001117}
1118
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001119TEST(Matcher, NestedOverloadedOperatorCalls) {
1120 EXPECT_TRUE(matchAndVerifyResultTrue(
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(hasOverloadedOperatorName("&&")).bind("x"),
1125 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1126 EXPECT_TRUE(matches(
1127 "class Y { }; "
1128 "Y& operator&&(Y& x, Y& y) { return x; }; "
1129 "Y a; Y b; Y c; Y d = a && b && c;",
1130 operatorCallExpr(hasParent(operatorCallExpr()))));
1131 EXPECT_TRUE(matches(
1132 "class Y { }; "
1133 "Y& operator&&(Y& x, Y& y) { return x; }; "
1134 "Y a; Y b; Y c; Y d = a && b && c;",
1135 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1136}
1137
Manuel Klimek04616e42012-07-06 05:48:52 +00001138TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001139 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001140 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001141
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 EXPECT_TRUE(
1152 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1153 MethodOnY));
1154 EXPECT_TRUE(
1155 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1156 MethodOnY));
1157
1158 EXPECT_TRUE(matches(
1159 "class Y {"
1160 " public: virtual void x();"
1161 "};"
1162 "class X : public Y {"
1163 " public: virtual void x();"
1164 "};"
1165 "void z() { X *x; x->Y::x(); }", MethodOnY));
1166}
1167
1168TEST(Matcher, VariableUsage) {
1169 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001170 declRefExpr(to(
1171 varDecl(hasInitializer(
1172 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001173
1174 EXPECT_TRUE(matches(
1175 "class Y {"
1176 " public:"
1177 " bool x() const;"
1178 "};"
1179 "void z(const Y &y) {"
1180 " bool b = y.x();"
1181 " if (b) {}"
1182 "}", Reference));
1183
1184 EXPECT_TRUE(notMatches(
1185 "class Y {"
1186 " public:"
1187 " bool x() const;"
1188 "};"
1189 "void z(const Y &y) {"
1190 " bool b = y.x();"
1191 "}", Reference));
1192}
1193
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001194TEST(Matcher, VarDecl_Storage) {
1195 auto M = varDecl(hasName("X"), hasLocalStorage());
1196 EXPECT_TRUE(matches("void f() { int X; }", M));
1197 EXPECT_TRUE(notMatches("int X;", M));
1198 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1199
1200 M = varDecl(hasName("X"), hasGlobalStorage());
1201 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1202 EXPECT_TRUE(matches("int X;", M));
1203 EXPECT_TRUE(matches("void f() { static int X; }", M));
1204}
1205
Manuel Klimek61379422012-12-04 14:42:08 +00001206TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001207 EXPECT_TRUE(matches(
1208 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001209 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001210}
1211
Manuel Klimek04616e42012-07-06 05:48:52 +00001212TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001213 StatementMatcher CallOnVariableY =
1214 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001215
1216 EXPECT_TRUE(matches(
1217 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1218 EXPECT_TRUE(matches(
1219 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1220 EXPECT_TRUE(matches(
1221 "class Y { public: void x(); };"
1222 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1223 EXPECT_TRUE(matches(
1224 "class Y { public: void x(); };"
1225 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1226 EXPECT_TRUE(notMatches(
1227 "class Y { public: void x(); };"
1228 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1229 CallOnVariableY));
1230}
1231
Daniel Jasper1dad1832012-07-10 20:20:19 +00001232TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1233 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1234 unaryExprOrTypeTraitExpr()));
1235 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1236 alignOfExpr(anything())));
1237 // FIXME: Uncomment once alignof is enabled.
1238 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1239 // unaryExprOrTypeTraitExpr()));
1240 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1241 // sizeOfExpr()));
1242}
1243
1244TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1245 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1246 hasArgumentOfType(asString("int")))));
1247 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1248 hasArgumentOfType(asString("float")))));
1249 EXPECT_TRUE(matches(
1250 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001251 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001252 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001253 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001254}
1255
Manuel Klimek04616e42012-07-06 05:48:52 +00001256TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001257 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001258}
1259
1260TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001261 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001262}
1263
1264TEST(MemberExpression, MatchesVariable) {
1265 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001266 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001267 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001268 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001269 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001270 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001271}
1272
1273TEST(MemberExpression, MatchesStaticVariable) {
1274 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001275 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001276 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001277 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001278 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001279 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001280}
1281
Daniel Jasper4e566c42012-07-12 08:50:38 +00001282TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001283 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1284 EXPECT_TRUE(matches(
1285 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1286 callExpr(hasArgument(0, declRefExpr(
1287 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001288}
1289
1290TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001291 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001292 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001293 callExpr(hasArgument(0, declRefExpr(
1294 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001295}
1296
Manuel Klimek04616e42012-07-06 05:48:52 +00001297TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1298 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001299 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001300 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001301 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001302 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001303 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001304}
1305
1306TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1307 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001308 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001309 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001310 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001311 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001312 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001313}
1314
1315TEST(IsArrow, MatchesMemberCallsViaArrow) {
1316 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001317 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001318 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001319 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001320 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001321 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001322}
1323
1324TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001325 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001326
1327 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1328 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1329}
1330
1331TEST(Callee, MatchesMemberExpressions) {
1332 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001333 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001334 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001335 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001336}
1337
1338TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001339 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001340
1341 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1342 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1343
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001344 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1345 llvm::Triple::Win32) {
1346 // FIXME: Make this work for MSVC.
1347 // Dependent contexts, but a non-dependent call.
1348 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1349 CallFunctionF));
1350 EXPECT_TRUE(
1351 matches("void f(); template <int N> struct S { void g() { f(); } };",
1352 CallFunctionF));
1353 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001354
1355 // Depedent calls don't match.
1356 EXPECT_TRUE(
1357 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1358 CallFunctionF));
1359 EXPECT_TRUE(
1360 notMatches("void f(int);"
1361 "template <typename T> struct S { void g(T t) { f(t); } };",
1362 CallFunctionF));
1363}
1364
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001365TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1366 EXPECT_TRUE(
1367 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001368 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001369}
1370
1371TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1372 EXPECT_TRUE(
1373 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001374 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001375}
1376
1377TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1378 EXPECT_TRUE(
1379 notMatches("void g(); template <typename T> void f(T t) {}"
1380 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001381 functionTemplateDecl(hasName("f"),
1382 hasDescendant(declRefExpr(to(
1383 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001384}
1385
Manuel Klimek04616e42012-07-06 05:48:52 +00001386TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001387 StatementMatcher CallArgumentY = callExpr(
1388 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001389
1390 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1391 EXPECT_TRUE(
1392 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1393 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1394
Daniel Jasper848cbe12012-09-18 13:09:13 +00001395 StatementMatcher WrongIndex = callExpr(
1396 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001397 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1398}
1399
1400TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001401 StatementMatcher CallArgumentY = callExpr(
1402 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001403 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1404 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1405 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1406}
1407
1408TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001409 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001410
1411 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1412 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1413 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1414}
1415
Daniel Jasper9f501292012-12-04 11:54:27 +00001416TEST(Matcher, ParameterCount) {
1417 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1418 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1419 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1420 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1421 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1422}
1423
Manuel Klimek04616e42012-07-06 05:48:52 +00001424TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001425 DeclarationMatcher ReferenceClassX = varDecl(
1426 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001427 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1428 ReferenceClassX));
1429 EXPECT_TRUE(
1430 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001431 // The match here is on the implicit copy constructor code for
1432 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001433 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001434 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1435 EXPECT_TRUE(
1436 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001437 EXPECT_TRUE(
1438 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1439}
1440
Edwin Vane0a4836e2013-03-06 17:02:57 +00001441TEST(QualType, hasCanonicalType) {
1442 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1443 "int a;"
1444 "int_ref b = a;",
1445 varDecl(hasType(qualType(referenceType())))));
1446 EXPECT_TRUE(
1447 matches("typedef int &int_ref;"
1448 "int a;"
1449 "int_ref b = a;",
1450 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1451}
1452
Edwin Vane119d3df2013-04-02 18:15:55 +00001453TEST(QualType, hasLocalQualifiers) {
1454 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1455 varDecl(hasType(hasLocalQualifiers()))));
1456 EXPECT_TRUE(matches("int *const j = nullptr;",
1457 varDecl(hasType(hasLocalQualifiers()))));
1458 EXPECT_TRUE(matches("int *volatile k;",
1459 varDecl(hasType(hasLocalQualifiers()))));
1460 EXPECT_TRUE(notMatches("int m;",
1461 varDecl(hasType(hasLocalQualifiers()))));
1462}
1463
Manuel Klimek04616e42012-07-06 05:48:52 +00001464TEST(HasParameter, CallsInnerMatcher) {
1465 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001466 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001467 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001468 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001469}
1470
1471TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1472 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001473 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001474}
1475
1476TEST(HasType, MatchesParameterVariableTypesStrictly) {
1477 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001478 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001479 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001480 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001481 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001482 methodDecl(hasParameter(0,
1483 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001484 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001485 methodDecl(hasParameter(0,
1486 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001487}
1488
1489TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1490 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001491 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001492 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001493 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001494}
1495
Daniel Jasper1dad1832012-07-10 20:20:19 +00001496TEST(Returns, MatchesReturnTypes) {
1497 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001498 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001499 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001500 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001501 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001502 functionDecl(returns(hasDeclaration(
1503 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001504}
1505
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001506TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001507 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1508 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1509 functionDecl(isExternC())));
1510 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001511}
1512
Manuel Klimek04616e42012-07-06 05:48:52 +00001513TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1514 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001515 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001516}
1517
1518TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1519 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001520 methodDecl(hasAnyParameter(hasType(pointsTo(
1521 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001522}
1523
Alp Toker8db6e7a2014-01-05 06:38:57 +00001524TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001525 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001526 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001527 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001528 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001529}
1530
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001531TEST(Matcher, MatchesClassTemplateSpecialization) {
1532 EXPECT_TRUE(matches("template<typename T> struct A {};"
1533 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001534 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001535 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001536 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001537 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001538 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001539}
1540
Manuel Klimekc16c6522013-06-20 13:08:29 +00001541TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1542 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1543 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1544}
1545
1546TEST(ParmVarDecl, MatchesParmVars) {
1547 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1548 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1549}
1550
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001551TEST(Matcher, MatchesTypeTemplateArgument) {
1552 EXPECT_TRUE(matches(
1553 "template<typename T> struct B {};"
1554 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001555 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001556 asString("int"))))));
1557}
1558
1559TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1560 EXPECT_TRUE(matches(
1561 "struct B { int next; };"
1562 "template<int(B::*next_ptr)> struct A {};"
1563 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001564 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1565 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001566
1567 EXPECT_TRUE(notMatches(
1568 "template <typename T> struct A {};"
1569 "A<int> a;",
1570 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1571 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001572
1573 EXPECT_TRUE(matches(
1574 "struct B { int next; };"
1575 "template<int(B::*next_ptr)> struct A {};"
1576 "A<&B::next> a;",
1577 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1578 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1579
1580 EXPECT_TRUE(notMatches(
1581 "template <typename T> struct A {};"
1582 "A<int> a;",
1583 templateSpecializationType(hasAnyTemplateArgument(
1584 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001585}
1586
1587TEST(Matcher, MatchesSpecificArgument) {
1588 EXPECT_TRUE(matches(
1589 "template<typename T, typename U> class A {};"
1590 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001591 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001592 1, refersToType(asString("int"))))));
1593 EXPECT_TRUE(notMatches(
1594 "template<typename T, typename U> class A {};"
1595 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001596 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001597 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001598
1599 EXPECT_TRUE(matches(
1600 "template<typename T, typename U> class A {};"
1601 "A<bool, int> a;",
1602 templateSpecializationType(hasTemplateArgument(
1603 1, refersToType(asString("int"))))));
1604 EXPECT_TRUE(notMatches(
1605 "template<typename T, typename U> class A {};"
1606 "A<int, bool> a;",
1607 templateSpecializationType(hasTemplateArgument(
1608 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001609}
1610
Daniel Jasper639522c2013-02-25 12:02:08 +00001611TEST(Matcher, MatchesAccessSpecDecls) {
1612 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1613 EXPECT_TRUE(
1614 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1615 EXPECT_TRUE(
1616 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1617 EXPECT_TRUE(
1618 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1619
1620 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1621}
1622
Edwin Vane37ee1d72013-04-09 20:46:36 +00001623TEST(Matcher, MatchesVirtualMethod) {
1624 EXPECT_TRUE(matches("class X { virtual int f(); };",
1625 methodDecl(isVirtual(), hasName("::X::f"))));
1626 EXPECT_TRUE(notMatches("class X { int f(); };",
1627 methodDecl(isVirtual())));
1628}
1629
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001630TEST(Matcher, MatchesPureMethod) {
1631 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1632 methodDecl(isPure(), hasName("::X::f"))));
1633 EXPECT_TRUE(notMatches("class X { int f(); };",
1634 methodDecl(isPure())));
1635}
1636
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001637TEST(Matcher, MatchesConstMethod) {
1638 EXPECT_TRUE(matches("struct A { void foo() const; };",
1639 methodDecl(isConst())));
1640 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1641 methodDecl(isConst())));
1642}
1643
Edwin Vane37ee1d72013-04-09 20:46:36 +00001644TEST(Matcher, MatchesOverridingMethod) {
1645 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1646 "class Y : public X { int f(); };",
1647 methodDecl(isOverride(), hasName("::Y::f"))));
1648 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1649 "class Y : public X { int f(); };",
1650 methodDecl(isOverride(), hasName("::X::f"))));
1651 EXPECT_TRUE(notMatches("class X { int f(); }; "
1652 "class Y : public X { int f(); };",
1653 methodDecl(isOverride())));
1654 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1655 methodDecl(isOverride())));
1656}
1657
Manuel Klimek04616e42012-07-06 05:48:52 +00001658TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001659 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001660
1661 EXPECT_TRUE(
1662 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1663 EXPECT_TRUE(
1664 matches("class X { public: X(); }; void x() { X x = X(); }",
1665 Constructor));
1666 EXPECT_TRUE(
1667 matches("class X { public: X(int); }; void x() { X x = 0; }",
1668 Constructor));
1669 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1670}
1671
1672TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001673 StatementMatcher Constructor = constructExpr(
1674 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001675
1676 EXPECT_TRUE(
1677 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1678 Constructor));
1679 EXPECT_TRUE(
1680 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1681 Constructor));
1682 EXPECT_TRUE(
1683 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1684 Constructor));
1685 EXPECT_TRUE(
1686 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1687 Constructor));
1688
Daniel Jasper848cbe12012-09-18 13:09:13 +00001689 StatementMatcher WrongIndex = constructExpr(
1690 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001691 EXPECT_TRUE(
1692 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1693 WrongIndex));
1694}
1695
1696TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001697 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001698
1699 EXPECT_TRUE(
1700 matches("class X { public: X(int); }; void x() { X x(0); }",
1701 Constructor1Arg));
1702 EXPECT_TRUE(
1703 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1704 Constructor1Arg));
1705 EXPECT_TRUE(
1706 matches("class X { public: X(int); }; void x() { X x = 0; }",
1707 Constructor1Arg));
1708 EXPECT_TRUE(
1709 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1710 Constructor1Arg));
1711}
1712
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001713TEST(Matcher, ConstructorListInitialization) {
1714 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1715
1716 EXPECT_TRUE(
1717 matches("class X { public: X(int); }; void x() { X x{0}; }",
1718 ConstructorListInit));
1719 EXPECT_FALSE(
1720 matches("class X { public: X(int); }; void x() { X x(0); }",
1721 ConstructorListInit));
1722}
1723
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001724TEST(Matcher,ThisExpr) {
1725 EXPECT_TRUE(
1726 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1727 EXPECT_TRUE(
1728 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1729}
1730
Manuel Klimek04616e42012-07-06 05:48:52 +00001731TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001732 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001733
1734 std::string ClassString = "class string { public: string(); ~string(); }; ";
1735
1736 EXPECT_TRUE(
1737 matches(ClassString +
1738 "string GetStringByValue();"
1739 "void FunctionTakesString(string s);"
1740 "void run() { FunctionTakesString(GetStringByValue()); }",
1741 TempExpression));
1742
1743 EXPECT_TRUE(
1744 notMatches(ClassString +
1745 "string* GetStringPointer(); "
1746 "void FunctionTakesStringPtr(string* s);"
1747 "void run() {"
1748 " string* s = GetStringPointer();"
1749 " FunctionTakesStringPtr(GetStringPointer());"
1750 " FunctionTakesStringPtr(s);"
1751 "}",
1752 TempExpression));
1753
1754 EXPECT_TRUE(
1755 notMatches("class no_dtor {};"
1756 "no_dtor GetObjByValue();"
1757 "void ConsumeObj(no_dtor param);"
1758 "void run() { ConsumeObj(GetObjByValue()); }",
1759 TempExpression));
1760}
1761
Sam Panzer68a35af2012-08-24 22:04:44 +00001762TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1763 std::string ClassString =
1764 "class string { public: string(); int length(); }; ";
1765
1766 EXPECT_TRUE(
1767 matches(ClassString +
1768 "string GetStringByValue();"
1769 "void FunctionTakesString(string s);"
1770 "void run() { FunctionTakesString(GetStringByValue()); }",
1771 materializeTemporaryExpr()));
1772
1773 EXPECT_TRUE(
1774 notMatches(ClassString +
1775 "string* GetStringPointer(); "
1776 "void FunctionTakesStringPtr(string* s);"
1777 "void run() {"
1778 " string* s = GetStringPointer();"
1779 " FunctionTakesStringPtr(GetStringPointer());"
1780 " FunctionTakesStringPtr(s);"
1781 "}",
1782 materializeTemporaryExpr()));
1783
1784 EXPECT_TRUE(
1785 notMatches(ClassString +
1786 "string GetStringByValue();"
1787 "void run() { int k = GetStringByValue().length(); }",
1788 materializeTemporaryExpr()));
1789
1790 EXPECT_TRUE(
1791 notMatches(ClassString +
1792 "string GetStringByValue();"
1793 "void run() { GetStringByValue(); }",
1794 materializeTemporaryExpr()));
1795}
1796
Manuel Klimek04616e42012-07-06 05:48:52 +00001797TEST(ConstructorDeclaration, SimpleCase) {
1798 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001799 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001800 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001801 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001802}
1803
1804TEST(ConstructorDeclaration, IsImplicit) {
1805 // This one doesn't match because the constructor is not added by the
1806 // compiler (it is not needed).
1807 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001808 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001809 // The compiler added the implicit default constructor.
1810 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001811 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001812 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001813 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001814 // The compiler added an implicit assignment operator.
1815 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1816 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001817}
1818
Daniel Jasper1dad1832012-07-10 20:20:19 +00001819TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1820 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001821 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001822}
1823
1824TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001825 EXPECT_TRUE(notMatches("class Foo {};",
1826 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001827}
1828
Manuel Klimek04616e42012-07-06 05:48:52 +00001829TEST(HasAnyConstructorInitializer, SimpleCase) {
1830 EXPECT_TRUE(notMatches(
1831 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001832 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001833 EXPECT_TRUE(matches(
1834 "class Foo {"
1835 " Foo() : foo_() { }"
1836 " int foo_;"
1837 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001838 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001839}
1840
1841TEST(HasAnyConstructorInitializer, ForField) {
1842 static const char Code[] =
1843 "class Baz { };"
1844 "class Foo {"
1845 " Foo() : foo_() { }"
1846 " Baz foo_;"
1847 " Baz bar_;"
1848 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001849 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1850 forField(hasType(recordDecl(hasName("Baz"))))))));
1851 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001852 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001853 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1854 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001855}
1856
1857TEST(HasAnyConstructorInitializer, WithInitializer) {
1858 static const char Code[] =
1859 "class Foo {"
1860 " Foo() : foo_(0) { }"
1861 " int foo_;"
1862 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001863 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001864 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001865 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001866 withInitializer(integerLiteral(equals(1)))))));
1867}
1868
1869TEST(HasAnyConstructorInitializer, IsWritten) {
1870 static const char Code[] =
1871 "struct Bar { Bar(){} };"
1872 "class Foo {"
1873 " Foo() : foo_() { }"
1874 " Bar foo_;"
1875 " Bar bar_;"
1876 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001877 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001878 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001879 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001880 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001881 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001882 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1883}
1884
1885TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001886 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001887
1888 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
1889 EXPECT_TRUE(
1890 matches("class X { public: X(); }; void x() { new X(); }", New));
1891 EXPECT_TRUE(
1892 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1893 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
1894}
1895
1896TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001897 StatementMatcher New = constructExpr(
1898 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001899
1900 EXPECT_TRUE(
1901 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1902 New));
1903 EXPECT_TRUE(
1904 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1905 New));
1906 EXPECT_TRUE(
1907 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
1908 New));
1909
Daniel Jasper848cbe12012-09-18 13:09:13 +00001910 StatementMatcher WrongIndex = constructExpr(
1911 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001912 EXPECT_TRUE(
1913 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
1914 WrongIndex));
1915}
1916
1917TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001918 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001919
1920 EXPECT_TRUE(
1921 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1922 EXPECT_TRUE(
1923 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
1924 New));
1925}
1926
Daniel Jasper1dad1832012-07-10 20:20:19 +00001927TEST(Matcher, DeleteExpression) {
1928 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001929 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001930}
1931
Manuel Klimek04616e42012-07-06 05:48:52 +00001932TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001933 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001934
1935 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
1936 EXPECT_TRUE(
1937 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
1938 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
1939}
1940
1941TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001942 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001943 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
1944 // wide string
1945 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
1946 // with escaped characters
1947 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
1948 // no matching -- though the data type is the same, there is no string literal
1949 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
1950}
1951
1952TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001953 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001954 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
1955 // wide character
1956 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
1957 // wide character, Hex encoded, NOT MATCHED!
1958 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
1959 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
1960}
1961
1962TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001963 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001964 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
1965 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
1966 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
1967 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
1968
1969 // Non-matching cases (character literals, float and double)
1970 EXPECT_TRUE(notMatches("int i = L'a';",
1971 HasIntLiteral)); // this is actually a character
1972 // literal cast to int
1973 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
1974 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
1975 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
1976}
1977
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00001978TEST(Matcher, FloatLiterals) {
1979 StatementMatcher HasFloatLiteral = floatLiteral();
1980 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
1981 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
1982 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
1983 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
1984 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
1985
1986 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
1987}
1988
Daniel Jasper5901e472012-10-01 13:40:41 +00001989TEST(Matcher, NullPtrLiteral) {
1990 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
1991}
1992
Daniel Jasper87c3d362012-09-20 14:12:57 +00001993TEST(Matcher, AsmStatement) {
1994 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1995}
1996
Manuel Klimek04616e42012-07-06 05:48:52 +00001997TEST(Matcher, Conditions) {
1998 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
1999
2000 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2001 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2002 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2003 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2004 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2005}
2006
Manuel Klimek909b5c942014-05-27 10:04:12 +00002007TEST(IfStmt, ChildTraversalMatchers) {
2008 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2009 ifStmt(hasThen(boolLiteral(equals(true))))));
2010 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2011 ifStmt(hasThen(boolLiteral(equals(true))))));
2012 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2013 ifStmt(hasElse(boolLiteral(equals(true))))));
2014 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2015 ifStmt(hasElse(boolLiteral(equals(true))))));
2016}
2017
Manuel Klimek04616e42012-07-06 05:48:52 +00002018TEST(MatchBinaryOperator, HasOperatorName) {
2019 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2020
2021 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2022 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2023}
2024
2025TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2026 StatementMatcher OperatorTrueFalse =
2027 binaryOperator(hasLHS(boolLiteral(equals(true))),
2028 hasRHS(boolLiteral(equals(false))));
2029
2030 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2031 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2032 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2033}
2034
2035TEST(MatchBinaryOperator, HasEitherOperand) {
2036 StatementMatcher HasOperand =
2037 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2038
2039 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2040 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2041 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2042}
2043
2044TEST(Matcher, BinaryOperatorTypes) {
2045 // Integration test that verifies the AST provides all binary operators in
2046 // a way we expect.
2047 // FIXME: Operator ','
2048 EXPECT_TRUE(
2049 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2050 EXPECT_TRUE(
2051 matches("bool b; bool c = (b = true);",
2052 binaryOperator(hasOperatorName("="))));
2053 EXPECT_TRUE(
2054 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2055 EXPECT_TRUE(
2056 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2057 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2058 EXPECT_TRUE(
2059 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2060 EXPECT_TRUE(
2061 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2062 EXPECT_TRUE(
2063 matches("int i = 1; int j = (i <<= 2);",
2064 binaryOperator(hasOperatorName("<<="))));
2065 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2066 EXPECT_TRUE(
2067 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2068 EXPECT_TRUE(
2069 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2070 EXPECT_TRUE(
2071 matches("int i = 1; int j = (i >>= 2);",
2072 binaryOperator(hasOperatorName(">>="))));
2073 EXPECT_TRUE(
2074 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2075 EXPECT_TRUE(
2076 matches("int i = 42; int j = (i ^= 42);",
2077 binaryOperator(hasOperatorName("^="))));
2078 EXPECT_TRUE(
2079 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2080 EXPECT_TRUE(
2081 matches("int i = 42; int j = (i %= 42);",
2082 binaryOperator(hasOperatorName("%="))));
2083 EXPECT_TRUE(
2084 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2085 EXPECT_TRUE(
2086 matches("bool b = true && false;",
2087 binaryOperator(hasOperatorName("&&"))));
2088 EXPECT_TRUE(
2089 matches("bool b = true; bool c = (b &= false);",
2090 binaryOperator(hasOperatorName("&="))));
2091 EXPECT_TRUE(
2092 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2093 EXPECT_TRUE(
2094 matches("bool b = true || false;",
2095 binaryOperator(hasOperatorName("||"))));
2096 EXPECT_TRUE(
2097 matches("bool b = true; bool c = (b |= false);",
2098 binaryOperator(hasOperatorName("|="))));
2099 EXPECT_TRUE(
2100 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2101 EXPECT_TRUE(
2102 matches("int i = 42; int j = (i *= 23);",
2103 binaryOperator(hasOperatorName("*="))));
2104 EXPECT_TRUE(
2105 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2106 EXPECT_TRUE(
2107 matches("int i = 42; int j = (i /= 23);",
2108 binaryOperator(hasOperatorName("/="))));
2109 EXPECT_TRUE(
2110 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2111 EXPECT_TRUE(
2112 matches("int i = 42; int j = (i += 23);",
2113 binaryOperator(hasOperatorName("+="))));
2114 EXPECT_TRUE(
2115 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2116 EXPECT_TRUE(
2117 matches("int i = 42; int j = (i -= 23);",
2118 binaryOperator(hasOperatorName("-="))));
2119 EXPECT_TRUE(
2120 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2121 binaryOperator(hasOperatorName("->*"))));
2122 EXPECT_TRUE(
2123 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2124 binaryOperator(hasOperatorName(".*"))));
2125
2126 // Member expressions as operators are not supported in matches.
2127 EXPECT_TRUE(
2128 notMatches("struct A { void x(A *a) { a->x(this); } };",
2129 binaryOperator(hasOperatorName("->"))));
2130
2131 // Initializer assignments are not represented as operator equals.
2132 EXPECT_TRUE(
2133 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2134
2135 // Array indexing is not represented as operator.
2136 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2137
2138 // Overloaded operators do not match at all.
2139 EXPECT_TRUE(notMatches(
2140 "struct A { bool operator&&(const A &a) const { return false; } };"
2141 "void x() { A a, b; a && b; }",
2142 binaryOperator()));
2143}
2144
2145TEST(MatchUnaryOperator, HasOperatorName) {
2146 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2147
2148 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2149 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2150}
2151
2152TEST(MatchUnaryOperator, HasUnaryOperand) {
2153 StatementMatcher OperatorOnFalse =
2154 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2155
2156 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2157 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2158}
2159
2160TEST(Matcher, UnaryOperatorTypes) {
2161 // Integration test that verifies the AST provides all unary operators in
2162 // a way we expect.
2163 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2164 EXPECT_TRUE(
2165 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2166 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2167 EXPECT_TRUE(
2168 matches("bool *p; bool b = *p;", 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 EXPECT_TRUE(
2176 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2177 EXPECT_TRUE(
2178 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2179 EXPECT_TRUE(
2180 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2181
2182 // We don't match conversion operators.
2183 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2184
2185 // Function calls are not represented as operator.
2186 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2187
2188 // Overloaded operators do not match at all.
2189 // FIXME: We probably want to add that.
2190 EXPECT_TRUE(notMatches(
2191 "struct A { bool operator!() const { return false; } };"
2192 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2193}
2194
2195TEST(Matcher, ConditionalOperator) {
2196 StatementMatcher Conditional = conditionalOperator(
2197 hasCondition(boolLiteral(equals(true))),
2198 hasTrueExpression(boolLiteral(equals(false))));
2199
2200 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2201 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2202 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2203
2204 StatementMatcher ConditionalFalse = conditionalOperator(
2205 hasFalseExpression(boolLiteral(equals(false))));
2206
2207 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2208 EXPECT_TRUE(
2209 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2210}
2211
Daniel Jasper1dad1832012-07-10 20:20:19 +00002212TEST(ArraySubscriptMatchers, ArraySubscripts) {
2213 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2214 arraySubscriptExpr()));
2215 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2216 arraySubscriptExpr()));
2217}
2218
2219TEST(ArraySubscriptMatchers, ArrayIndex) {
2220 EXPECT_TRUE(matches(
2221 "int i[2]; void f() { i[1] = 1; }",
2222 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2223 EXPECT_TRUE(matches(
2224 "int i[2]; void f() { 1[i] = 1; }",
2225 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2226 EXPECT_TRUE(notMatches(
2227 "int i[2]; void f() { i[1] = 1; }",
2228 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2229}
2230
2231TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2232 EXPECT_TRUE(matches(
2233 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002234 arraySubscriptExpr(hasBase(implicitCastExpr(
2235 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002236}
2237
Manuel Klimek04616e42012-07-06 05:48:52 +00002238TEST(Matcher, HasNameSupportsNamespaces) {
2239 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002240 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002241 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002242 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002243 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002244 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002245 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002246 recordDecl(hasName("C"))));
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::b::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("a::c::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("a::b::A"))));
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("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002255 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002256 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002257 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002258 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002259 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002260 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002261 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002262 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002263}
2264
2265TEST(Matcher, HasNameSupportsOuterClasses) {
2266 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002267 matches("class A { class B { class C; }; };",
2268 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002269 EXPECT_TRUE(
2270 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002271 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002272 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002273 matches("class A { class B { class C; }; };",
2274 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002275 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002276 matches("class A { class B { class C; }; };",
2277 recordDecl(hasName("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("c::B::C"))));
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("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002284 EXPECT_TRUE(
2285 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002286 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002287 EXPECT_TRUE(
2288 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002289 recordDecl(hasName("::C"))));
2290 EXPECT_TRUE(
2291 notMatches("class A { class B { class C; }; };",
2292 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002293 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002294 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002295 EXPECT_TRUE(
2296 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002297 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002298}
2299
2300TEST(Matcher, IsDefinition) {
2301 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002302 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002303 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2304 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2305
2306 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002307 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002308 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2309 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2310
2311 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002312 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002313 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2314 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2315}
2316
2317TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002318 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002319 ofClass(hasName("X")))));
2320
2321 EXPECT_TRUE(
2322 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2323 EXPECT_TRUE(
2324 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2325 Constructor));
2326 EXPECT_TRUE(
2327 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2328 Constructor));
2329}
2330
2331TEST(Matcher, VisitsTemplateInstantiations) {
2332 EXPECT_TRUE(matches(
2333 "class A { public: void x(); };"
2334 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002335 "void f() { B<A> b; b.y(); }",
2336 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002337
2338 EXPECT_TRUE(matches(
2339 "class A { public: void x(); };"
2340 "class C {"
2341 " public:"
2342 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2343 "};"
2344 "void f() {"
2345 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002346 "}",
2347 recordDecl(hasName("C"),
2348 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002349}
2350
Daniel Jasper1dad1832012-07-10 20:20:19 +00002351TEST(Matcher, HandlesNullQualTypes) {
2352 // FIXME: Add a Type matcher so we can replace uses of this
2353 // variable with Type(True())
2354 const TypeMatcher AnyType = anything();
2355
2356 // We don't really care whether this matcher succeeds; we're testing that
2357 // it completes without crashing.
2358 EXPECT_TRUE(matches(
2359 "struct A { };"
2360 "template <typename T>"
2361 "void f(T t) {"
2362 " T local_t(t /* this becomes a null QualType in the AST */);"
2363 "}"
2364 "void g() {"
2365 " f(0);"
2366 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002367 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002368 anyOf(
2369 TypeMatcher(hasDeclaration(anything())),
2370 pointsTo(AnyType),
2371 references(AnyType)
2372 // Other QualType matchers should go here.
2373 ))))));
2374}
2375
Manuel Klimek04616e42012-07-06 05:48:52 +00002376// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002377AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002378 // Make sure all special variables are used: node, match_finder,
2379 // bound_nodes_builder, and the parameter named 'AMatcher'.
2380 return AMatcher.matches(Node, Finder, Builder);
2381}
2382
2383TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002384 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002385
2386 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002387 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002388
2389 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002390 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002391
2392 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002393 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002394}
2395
2396AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +00002397 polymorphicHas,
2398 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2399 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002400 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002401 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002402 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2403 ASTMatchFinder::BK_First);
2404}
2405
2406TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002407 DeclarationMatcher HasClassB =
2408 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002409
2410 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002411 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002412
2413 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002414 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002415
2416 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002417 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002418
2419 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002420 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002421
2422 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2423}
2424
2425TEST(For, FindsForLoops) {
2426 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2427 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002428 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2429 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002430 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002431}
2432
Daniel Jasper4e566c42012-07-12 08:50:38 +00002433TEST(For, ForLoopInternals) {
2434 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2435 forStmt(hasCondition(anything()))));
2436 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2437 forStmt(hasLoopInit(anything()))));
2438}
2439
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002440TEST(For, ForRangeLoopInternals) {
2441 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2442 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002443 EXPECT_TRUE(matches(
2444 "void f(){ int a[] {1, 2}; for (int i : a); }",
2445 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002446}
2447
Daniel Jasper4e566c42012-07-12 08:50:38 +00002448TEST(For, NegativeForLoopInternals) {
2449 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002450 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002451 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2452 forStmt(hasLoopInit(anything()))));
2453}
2454
Manuel Klimek04616e42012-07-06 05:48:52 +00002455TEST(For, ReportsNoFalsePositives) {
2456 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2457 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2458}
2459
2460TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002461 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2462 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2463 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002464}
2465
2466TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2467 // It's not a compound statement just because there's "{}" in the source
2468 // text. This is an AST search, not grep.
2469 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002470 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002471 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002472 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002473}
2474
Daniel Jasper4e566c42012-07-12 08:50:38 +00002475TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002476 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002477 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002478 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002479 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002480 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002481 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002482 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002483 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002484 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2485 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002486}
2487
2488TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2489 // The simplest case: every compound statement is in a function
2490 // definition, and the function body itself must be a compound
2491 // statement.
2492 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002493 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002494}
2495
2496TEST(HasAnySubstatement, IsNotRecursive) {
2497 // It's really "has any immediate substatement".
2498 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002499 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002500}
2501
2502TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2503 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002504 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002505}
2506
2507TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2508 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002509 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002510}
2511
2512TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2513 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002514 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002515 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002516 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002517}
2518
2519TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2520 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002521 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002522 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002523 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002524 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002525 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002526}
2527
2528TEST(StatementCountIs, WorksWithMultipleStatements) {
2529 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002530 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002531}
2532
2533TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2534 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002535 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002536 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002537 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002538 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002539 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002540 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002541 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002542}
2543
2544TEST(Member, WorksInSimplestCase) {
2545 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002546 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002547}
2548
2549TEST(Member, DoesNotMatchTheBaseExpression) {
2550 // Don't pick out the wrong part of the member expression, this should
2551 // be checking the member (name) only.
2552 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002553 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002554}
2555
2556TEST(Member, MatchesInMemberFunctionCall) {
2557 EXPECT_TRUE(matches("void f() {"
2558 " struct { void first() {}; } s;"
2559 " s.first();"
2560 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002561 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002562}
2563
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002564TEST(Member, MatchesMember) {
2565 EXPECT_TRUE(matches(
2566 "struct A { int i; }; void f() { A a; a.i = 2; }",
2567 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2568 EXPECT_TRUE(notMatches(
2569 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2570 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2571}
2572
Daniel Jasper639522c2013-02-25 12:02:08 +00002573TEST(Member, UnderstandsAccess) {
2574 EXPECT_TRUE(matches(
2575 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2576 EXPECT_TRUE(notMatches(
2577 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2578 EXPECT_TRUE(notMatches(
2579 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2580
2581 EXPECT_TRUE(notMatches(
2582 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2583 EXPECT_TRUE(notMatches(
2584 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2585 EXPECT_TRUE(matches(
2586 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2587
2588 EXPECT_TRUE(notMatches(
2589 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2590 EXPECT_TRUE(matches("class A { protected: int i; };",
2591 fieldDecl(isProtected(), hasName("i"))));
2592 EXPECT_TRUE(notMatches(
2593 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2594
2595 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2596 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2597 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2598 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2599}
2600
Dmitri Gribenko06963042012-08-18 00:29:27 +00002601TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002602 // Fails in C++11 mode
2603 EXPECT_TRUE(matchesConditionally(
2604 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2605 "class X { void *operator new(std::size_t); };",
2606 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002607
2608 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002609 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002610
Daniel Jasper5901e472012-10-01 13:40:41 +00002611 // Fails in C++11 mode
2612 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002613 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2614 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002615 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002616}
2617
Manuel Klimek04616e42012-07-06 05:48:52 +00002618TEST(HasObjectExpression, DoesNotMatchMember) {
2619 EXPECT_TRUE(notMatches(
2620 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002621 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002622}
2623
2624TEST(HasObjectExpression, MatchesBaseOfVariable) {
2625 EXPECT_TRUE(matches(
2626 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002627 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002628 EXPECT_TRUE(matches(
2629 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002630 memberExpr(hasObjectExpression(
2631 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002632}
2633
2634TEST(HasObjectExpression,
2635 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2636 EXPECT_TRUE(matches(
2637 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002638 memberExpr(hasObjectExpression(
2639 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002640 EXPECT_TRUE(matches(
2641 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002642 memberExpr(hasObjectExpression(
2643 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002644}
2645
2646TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002647 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2648 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2649 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2650 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002651}
2652
2653TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002654 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002655}
2656
2657TEST(IsConstQualified, MatchesConstInt) {
2658 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002659 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002660}
2661
2662TEST(IsConstQualified, MatchesConstPointer) {
2663 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002664 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002665}
2666
2667TEST(IsConstQualified, MatchesThroughTypedef) {
2668 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002669 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002670 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002671 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002672}
2673
2674TEST(IsConstQualified, DoesNotMatchInappropriately) {
2675 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002676 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002677 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002678 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002679}
2680
Sam Panzer80c13772012-08-16 16:58:10 +00002681TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002682 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2683 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2684 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2685 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002686}
2687TEST(CastExpression, MatchesImplicitCasts) {
2688 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002689 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002690 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002691 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002692}
2693
2694TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002695 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2696 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2697 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2698 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002699}
2700
Manuel Klimek04616e42012-07-06 05:48:52 +00002701TEST(ReinterpretCast, MatchesSimpleCase) {
2702 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002703 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002704}
2705
2706TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002707 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002708 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002709 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002710 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002711 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002712 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2713 "B b;"
2714 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002715 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002716}
2717
2718TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002719 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002720 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002721 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002722}
2723
2724TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002725 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002726 EXPECT_TRUE(
2727 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002728 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002729 EXPECT_TRUE(
2730 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002731 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002732}
2733
2734TEST(DynamicCast, MatchesSimpleCase) {
2735 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2736 "B b;"
2737 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002738 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002739}
2740
2741TEST(StaticCast, MatchesSimpleCase) {
2742 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002743 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002744}
2745
2746TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002747 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002748 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002749 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002750 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002751 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002752 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2753 "B b;"
2754 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002755 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002756}
2757
Daniel Jasper417f7762012-09-18 13:36:17 +00002758TEST(CStyleCast, MatchesSimpleCase) {
2759 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2760}
2761
2762TEST(CStyleCast, DoesNotMatchOtherCasts) {
2763 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2764 "char q, *r = const_cast<char*>(&q);"
2765 "void* s = reinterpret_cast<char*>(&s);"
2766 "struct B { virtual ~B() {} }; struct D : B {};"
2767 "B b;"
2768 "D* t = dynamic_cast<D*>(&b);",
2769 cStyleCastExpr()));
2770}
2771
Manuel Klimek04616e42012-07-06 05:48:52 +00002772TEST(HasDestinationType, MatchesSimpleCase) {
2773 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002774 staticCastExpr(hasDestinationType(
2775 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002776}
2777
Sam Panzer80c13772012-08-16 16:58:10 +00002778TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2779 // This test creates an implicit const cast.
2780 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002781 implicitCastExpr(
2782 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002783 // This test creates an implicit array-to-pointer cast.
2784 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002785 implicitCastExpr(hasImplicitDestinationType(
2786 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002787}
2788
2789TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2790 // This test creates an implicit cast from int to char.
2791 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002792 implicitCastExpr(hasImplicitDestinationType(
2793 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002794 // This test creates an implicit array-to-pointer cast.
2795 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002796 implicitCastExpr(hasImplicitDestinationType(
2797 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002798}
2799
2800TEST(ImplicitCast, MatchesSimpleCase) {
2801 // This test creates an implicit const cast.
2802 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002803 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002804 // This test creates an implicit cast from int to char.
2805 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002806 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002807 // This test creates an implicit array-to-pointer cast.
2808 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002809 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002810}
2811
2812TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002813 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002814 // are present, and that it ignores explicit and paren casts.
2815
2816 // These two test cases have no casts.
2817 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002818 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002819 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002820 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002821
2822 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002823 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002824 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002825 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002826
2827 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002828 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002829}
2830
2831TEST(IgnoringImpCasts, MatchesImpCasts) {
2832 // This test checks that ignoringImpCasts matches when implicit casts are
2833 // present and its inner matcher alone does not match.
2834 // Note that this test creates an implicit const cast.
2835 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002836 varDecl(hasInitializer(ignoringImpCasts(
2837 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002838 // This test creates an implict cast from int to char.
2839 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002840 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002841 integerLiteral(equals(0)))))));
2842}
2843
2844TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2845 // These tests verify that ignoringImpCasts does not match if the inner
2846 // matcher does not match.
2847 // Note that the first test creates an implicit const cast.
2848 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002849 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002850 unless(anything()))))));
2851 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002852 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002853 unless(anything()))))));
2854
2855 // These tests verify that ignoringImplictCasts does not look through explicit
2856 // casts or parentheses.
2857 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(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("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002861 varDecl(hasInitializer(ignoringImpCasts(
2862 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002863 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002864 varDecl(hasInitializer(ignoringImpCasts(
2865 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002866 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002867 varDecl(hasInitializer(ignoringImpCasts(
2868 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002869}
2870
2871TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2872 // This test verifies that expressions that do not have implicit casts
2873 // still match the inner matcher.
2874 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002875 varDecl(hasInitializer(ignoringImpCasts(
2876 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002877}
2878
2879TEST(IgnoringParenCasts, MatchesParenCasts) {
2880 // This test checks that ignoringParenCasts matches when parentheses and/or
2881 // casts are present and its inner matcher alone does not match.
2882 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002883 varDecl(hasInitializer(ignoringParenCasts(
2884 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002885 EXPECT_TRUE(matches("int 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 // This test creates an implict cast from int to char in addition to the
2890 // parentheses.
2891 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002892 varDecl(hasInitializer(ignoringParenCasts(
2893 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002894
2895 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002896 varDecl(hasInitializer(ignoringParenCasts(
2897 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002898 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002899 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002900 integerLiteral(equals(0)))))));
2901}
2902
2903TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
2904 // This test verifies that expressions that do not have any casts still match.
2905 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002906 varDecl(hasInitializer(ignoringParenCasts(
2907 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002908}
2909
2910TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
2911 // These tests verify that ignoringImpCasts does not match if the inner
2912 // matcher does not match.
2913 EXPECT_TRUE(notMatches("int 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 // This test creates an implicit cast from int to char in addition to the
2918 // parentheses.
2919 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002920 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002921 unless(anything()))))));
2922
2923 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002924 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002925 unless(anything()))))));
2926}
2927
2928TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
2929 // This test checks that ignoringParenAndImpCasts matches when
2930 // parentheses and/or implicit casts are present and its inner matcher alone
2931 // does not match.
2932 // Note that this test creates an implicit const cast.
2933 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002934 varDecl(hasInitializer(ignoringParenImpCasts(
2935 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002936 // This test creates an implicit cast from int to char.
2937 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002938 varDecl(hasInitializer(ignoringParenImpCasts(
2939 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002940}
2941
2942TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
2943 // This test verifies that expressions that do not have parentheses or
2944 // implicit casts still match.
2945 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002946 varDecl(hasInitializer(ignoringParenImpCasts(
2947 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002948 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002949 varDecl(hasInitializer(ignoringParenImpCasts(
2950 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002951}
2952
2953TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
2954 // These tests verify that ignoringParenImpCasts does not match if
2955 // the inner matcher does not match.
2956 // This test creates an implicit cast.
2957 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002958 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002959 unless(anything()))))));
2960 // These tests verify that ignoringParenAndImplictCasts does not look
2961 // through explicit casts.
2962 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002963 varDecl(hasInitializer(ignoringParenImpCasts(
2964 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002965 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002966 varDecl(hasInitializer(ignoringParenImpCasts(
2967 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002968 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002969 varDecl(hasInitializer(ignoringParenImpCasts(
2970 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002971}
2972
Manuel Klimeke9235692012-07-25 10:02:02 +00002973TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002974 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
2975 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002976 implicitCastExpr(
2977 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002978}
2979
Manuel Klimeke9235692012-07-25 10:02:02 +00002980TEST(HasSourceExpression, MatchesExplicitCasts) {
2981 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002982 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002983 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002984 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00002985}
2986
Manuel Klimek04616e42012-07-06 05:48:52 +00002987TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002988 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002989}
2990
2991TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002992 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002993}
2994
2995TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002996 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002997}
2998
2999TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003000 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003001}
3002
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003003TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3004 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3005 "const Foo f = Foo();",
3006 varDecl(hasInitializer(exprWithCleanups()))));
3007 EXPECT_FALSE(matches("struct Foo { };"
3008 "const Foo f = Foo();",
3009 varDecl(hasInitializer(exprWithCleanups()))));
3010}
3011
Daniel Jasper1dad1832012-07-10 20:20:19 +00003012TEST(InitListExpression, MatchesInitListExpression) {
3013 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3014 initListExpr(hasType(asString("int [2]")))));
3015 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003016 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003017}
3018
3019TEST(UsingDeclaration, MatchesUsingDeclarations) {
3020 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3021 usingDecl()));
3022}
3023
3024TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3025 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3026 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3027}
3028
3029TEST(UsingDeclaration, MatchesSpecificTarget) {
3030 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3031 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003032 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003033 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3034 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003035 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003036}
3037
3038TEST(UsingDeclaration, ThroughUsingDeclaration) {
3039 EXPECT_TRUE(matches(
3040 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003041 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003042 EXPECT_TRUE(notMatches(
3043 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003044 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003045}
3046
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003047TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3048 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3049 usingDirectiveDecl()));
3050 EXPECT_FALSE(
3051 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3052}
3053
Sam Panzerd624bfb2012-08-16 17:20:59 +00003054TEST(SingleDecl, IsSingleDecl) {
3055 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003056 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003057 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3058 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3059 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3060 SingleDeclStmt));
3061}
3062
3063TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003064 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003065
3066 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003067 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003068 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003069 declStmt(containsDeclaration(0, MatchesInit),
3070 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003071 unsigned WrongIndex = 42;
3072 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003073 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003074 MatchesInit))));
3075}
3076
3077TEST(DeclCount, DeclCountIsCorrect) {
3078 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003079 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003080 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003081 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003082 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003083 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003084}
3085
Manuel Klimek04616e42012-07-06 05:48:52 +00003086TEST(While, MatchesWhileLoops) {
3087 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3088 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3089 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3090}
3091
3092TEST(Do, MatchesDoLoops) {
3093 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3094 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3095}
3096
3097TEST(Do, DoesNotMatchWhileLoops) {
3098 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3099}
3100
3101TEST(SwitchCase, MatchesCase) {
3102 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3103 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3104 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3105 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3106}
3107
Daniel Jasper87c3d362012-09-20 14:12:57 +00003108TEST(SwitchCase, MatchesSwitch) {
3109 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3110 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3111 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3112 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3113}
3114
Peter Collingbourne3154a102013-05-10 11:52:02 +00003115TEST(SwitchCase, MatchesEachCase) {
3116 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3117 switchStmt(forEachSwitchCase(caseStmt()))));
3118 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3119 switchStmt(forEachSwitchCase(caseStmt()))));
3120 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3121 switchStmt(forEachSwitchCase(caseStmt()))));
3122 EXPECT_TRUE(notMatches(
3123 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3124 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3125 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3126 switchStmt(forEachSwitchCase(
3127 caseStmt(hasCaseConstant(integerLiteral()))))));
3128 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3129 switchStmt(forEachSwitchCase(
3130 caseStmt(hasCaseConstant(integerLiteral()))))));
3131 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3132 switchStmt(forEachSwitchCase(
3133 caseStmt(hasCaseConstant(integerLiteral()))))));
3134 EXPECT_TRUE(matchAndVerifyResultTrue(
3135 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3136 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3137 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3138}
3139
Manuel Klimekba46fc02013-07-19 11:50:54 +00003140TEST(ForEachConstructorInitializer, MatchesInitializers) {
3141 EXPECT_TRUE(matches(
3142 "struct X { X() : i(42), j(42) {} int i, j; };",
3143 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3144}
3145
Daniel Jasper87c3d362012-09-20 14:12:57 +00003146TEST(ExceptionHandling, SimpleCases) {
3147 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3148 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3149 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3150 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3151 throwExpr()));
3152 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3153 throwExpr()));
3154}
3155
Manuel Klimek04616e42012-07-06 05:48:52 +00003156TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3157 EXPECT_TRUE(notMatches(
3158 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003159 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003160 EXPECT_TRUE(notMatches(
3161 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003162 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003163}
3164
3165TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3166 EXPECT_TRUE(matches(
3167 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003168 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003169}
3170
3171TEST(ForEach, BindsOneNode) {
3172 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003173 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003174 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003175}
3176
3177TEST(ForEach, BindsMultipleNodes) {
3178 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003179 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003180 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003181}
3182
3183TEST(ForEach, BindsRecursiveCombinations) {
3184 EXPECT_TRUE(matchAndVerifyResultTrue(
3185 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003186 recordDecl(hasName("C"),
3187 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003188 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003189}
3190
3191TEST(ForEachDescendant, BindsOneNode) {
3192 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003193 recordDecl(hasName("C"),
3194 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003195 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003196}
3197
Daniel Jasper94a56852012-11-16 18:39:22 +00003198TEST(ForEachDescendant, NestedForEachDescendant) {
3199 DeclarationMatcher m = recordDecl(
3200 isDefinition(), decl().bind("x"), hasName("C"));
3201 EXPECT_TRUE(matchAndVerifyResultTrue(
3202 "class A { class B { class C {}; }; };",
3203 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3204 new VerifyIdIsBoundTo<Decl>("x", "C")));
3205
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003206 // Check that a partial match of 'm' that binds 'x' in the
3207 // first part of anyOf(m, anything()) will not overwrite the
3208 // binding created by the earlier binding in the hasDescendant.
3209 EXPECT_TRUE(matchAndVerifyResultTrue(
3210 "class A { class B { class C {}; }; };",
3211 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3212 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003213}
3214
Manuel Klimek04616e42012-07-06 05:48:52 +00003215TEST(ForEachDescendant, BindsMultipleNodes) {
3216 EXPECT_TRUE(matchAndVerifyResultTrue(
3217 "class C { class D { int x; int y; }; "
3218 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003219 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003220 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003221}
3222
3223TEST(ForEachDescendant, BindsRecursiveCombinations) {
3224 EXPECT_TRUE(matchAndVerifyResultTrue(
3225 "class C { class D { "
3226 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003227 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3228 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003229 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003230}
3231
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003232TEST(ForEachDescendant, BindsCombinations) {
3233 EXPECT_TRUE(matchAndVerifyResultTrue(
3234 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3235 "(true) {} }",
3236 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3237 forEachDescendant(whileStmt().bind("while"))),
3238 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3239}
3240
3241TEST(Has, DoesNotDeleteBindings) {
3242 EXPECT_TRUE(matchAndVerifyResultTrue(
3243 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3244 new VerifyIdIsBoundTo<Decl>("x", 1)));
3245}
3246
3247TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3248 // Those matchers cover all the cases where an inner matcher is called
3249 // and there is not a 1:1 relationship between the match of the outer
3250 // matcher and the match of the inner matcher.
3251 // The pattern to look for is:
3252 // ... return InnerMatcher.matches(...); ...
3253 // In which case no special handling is needed.
3254 //
3255 // On the other hand, if there are multiple alternative matches
3256 // (for example forEach*) or matches might be discarded (for example has*)
3257 // the implementation must make sure that the discarded matches do not
3258 // affect the bindings.
3259 // When new such matchers are added, add a test here that:
3260 // - matches a simple node, and binds it as the first thing in the matcher:
3261 // recordDecl(decl().bind("x"), hasName("X")))
3262 // - uses the matcher under test afterwards in a way that not the first
3263 // alternative is matched; for anyOf, that means the first branch
3264 // would need to return false; for hasAncestor, it means that not
3265 // the direct parent matches the inner matcher.
3266
3267 EXPECT_TRUE(matchAndVerifyResultTrue(
3268 "class X { int y; };",
3269 recordDecl(
3270 recordDecl().bind("x"), hasName("::X"),
3271 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3272 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3273 EXPECT_TRUE(matchAndVerifyResultTrue(
3274 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3275 anyOf(unless(anything()), anything())),
3276 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3277 EXPECT_TRUE(matchAndVerifyResultTrue(
3278 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3279 classTemplateSpecializationDecl(
3280 decl().bind("x"),
3281 hasAnyTemplateArgument(refersToType(asString("int")))),
3282 new VerifyIdIsBoundTo<Decl>("x", 1)));
3283 EXPECT_TRUE(matchAndVerifyResultTrue(
3284 "class X { void f(); void g(); };",
3285 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3286 new VerifyIdIsBoundTo<Decl>("x", 1)));
3287 EXPECT_TRUE(matchAndVerifyResultTrue(
3288 "class X { X() : a(1), b(2) {} double a; int b; };",
3289 recordDecl(decl().bind("x"),
3290 has(constructorDecl(
3291 hasAnyConstructorInitializer(forField(hasName("b")))))),
3292 new VerifyIdIsBoundTo<Decl>("x", 1)));
3293 EXPECT_TRUE(matchAndVerifyResultTrue(
3294 "void x(int, int) { x(0, 42); }",
3295 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3296 new VerifyIdIsBoundTo<Expr>("x", 1)));
3297 EXPECT_TRUE(matchAndVerifyResultTrue(
3298 "void x(int, int y) {}",
3299 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3300 new VerifyIdIsBoundTo<Decl>("x", 1)));
3301 EXPECT_TRUE(matchAndVerifyResultTrue(
3302 "void x() { return; if (true) {} }",
3303 functionDecl(decl().bind("x"),
3304 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3305 new VerifyIdIsBoundTo<Decl>("x", 1)));
3306 EXPECT_TRUE(matchAndVerifyResultTrue(
3307 "namespace X { void b(int); void b(); }"
3308 "using X::b;",
3309 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3310 functionDecl(parameterCountIs(1))))),
3311 new VerifyIdIsBoundTo<Decl>("x", 1)));
3312 EXPECT_TRUE(matchAndVerifyResultTrue(
3313 "class A{}; class B{}; class C : B, A {};",
3314 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3315 new VerifyIdIsBoundTo<Decl>("x", 1)));
3316 EXPECT_TRUE(matchAndVerifyResultTrue(
3317 "class A{}; typedef A B; typedef A C; typedef A D;"
3318 "class E : A {};",
3319 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3320 new VerifyIdIsBoundTo<Decl>("x", 1)));
3321 EXPECT_TRUE(matchAndVerifyResultTrue(
3322 "class A { class B { void f() {} }; };",
3323 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3324 new VerifyIdIsBoundTo<Decl>("x", 1)));
3325 EXPECT_TRUE(matchAndVerifyResultTrue(
3326 "template <typename T> struct A { struct B {"
3327 " void f() { if(true) {} }"
3328 "}; };"
3329 "void t() { A<int>::B b; b.f(); }",
3330 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3331 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3332 EXPECT_TRUE(matchAndVerifyResultTrue(
3333 "class A {};",
3334 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3335 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003336 EXPECT_TRUE(matchAndVerifyResultTrue(
3337 "class A { A() : s(), i(42) {} const char *s; int i; };",
3338 constructorDecl(hasName("::A::A"), decl().bind("x"),
3339 forEachConstructorInitializer(forField(hasName("i")))),
3340 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003341}
3342
Daniel Jasper33806cd2012-11-11 22:14:55 +00003343TEST(ForEachDescendant, BindsCorrectNodes) {
3344 EXPECT_TRUE(matchAndVerifyResultTrue(
3345 "class C { void f(); int i; };",
3346 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3347 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3348 EXPECT_TRUE(matchAndVerifyResultTrue(
3349 "class C { void f() {} int i; };",
3350 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3351 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3352}
3353
Manuel Klimekabf43712013-02-04 10:59:20 +00003354TEST(FindAll, BindsNodeOnMatch) {
3355 EXPECT_TRUE(matchAndVerifyResultTrue(
3356 "class A {};",
3357 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3358 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3359}
3360
3361TEST(FindAll, BindsDescendantNodeOnMatch) {
3362 EXPECT_TRUE(matchAndVerifyResultTrue(
3363 "class A { int a; int b; };",
3364 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3365 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3366}
3367
3368TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3369 EXPECT_TRUE(matchAndVerifyResultTrue(
3370 "class A { int a; int b; };",
3371 recordDecl(hasName("::A"),
3372 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3373 fieldDecl().bind("v"))))),
3374 new VerifyIdIsBoundTo<Decl>("v", 3)));
3375
3376 EXPECT_TRUE(matchAndVerifyResultTrue(
3377 "class A { class B {}; class C {}; };",
3378 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3379 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3380}
3381
Manuel Klimek88b95872013-02-04 09:42:38 +00003382TEST(EachOf, TriggersForEachMatch) {
3383 EXPECT_TRUE(matchAndVerifyResultTrue(
3384 "class A { int a; int b; };",
3385 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3386 has(fieldDecl(hasName("b")).bind("v")))),
3387 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3388}
3389
3390TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3391 EXPECT_TRUE(matchAndVerifyResultTrue(
3392 "class A { int a; int c; };",
3393 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3394 has(fieldDecl(hasName("b")).bind("v")))),
3395 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3396 EXPECT_TRUE(matchAndVerifyResultTrue(
3397 "class A { int c; int b; };",
3398 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3399 has(fieldDecl(hasName("b")).bind("v")))),
3400 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3401 EXPECT_TRUE(notMatches(
3402 "class A { int c; int d; };",
3403 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3404 has(fieldDecl(hasName("b")).bind("v"))))));
3405}
Manuel Klimek04616e42012-07-06 05:48:52 +00003406
3407TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3408 // Make sure that we can both match the class by name (::X) and by the type
3409 // the template was instantiated with (via a field).
3410
3411 EXPECT_TRUE(matches(
3412 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003413 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003414
3415 EXPECT_TRUE(matches(
3416 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003417 recordDecl(isTemplateInstantiation(), hasDescendant(
3418 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003419}
3420
3421TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3422 EXPECT_TRUE(matches(
3423 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003424 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003425 isTemplateInstantiation())));
3426}
3427
3428TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3429 EXPECT_TRUE(matches(
3430 "template <typename T> class X { T t; }; class A {};"
3431 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003432 recordDecl(isTemplateInstantiation(), hasDescendant(
3433 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003434}
3435
3436TEST(IsTemplateInstantiation,
3437 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3438 EXPECT_TRUE(matches(
3439 "template <typename T> class X {};"
3440 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003441 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003442}
3443
3444TEST(IsTemplateInstantiation,
3445 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3446 EXPECT_TRUE(matches(
3447 "class A {};"
3448 "class X {"
3449 " template <typename U> class Y { U u; };"
3450 " Y<A> y;"
3451 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003452 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003453}
3454
3455TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3456 // FIXME: Figure out whether this makes sense. It doesn't affect the
3457 // normal use case as long as the uppermost instantiation always is marked
3458 // as template instantiation, but it might be confusing as a predicate.
3459 EXPECT_TRUE(matches(
3460 "class A {};"
3461 "template <typename T> class X {"
3462 " template <typename U> class Y { U u; };"
3463 " Y<T> y;"
3464 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003465 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003466}
3467
3468TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3469 EXPECT_TRUE(notMatches(
3470 "template <typename T> class X {}; class A {};"
3471 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003472 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003473}
3474
3475TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3476 EXPECT_TRUE(notMatches(
3477 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003478 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003479}
3480
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003481TEST(IsExplicitTemplateSpecialization,
3482 DoesNotMatchPrimaryTemplate) {
3483 EXPECT_TRUE(notMatches(
3484 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003485 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003486 EXPECT_TRUE(notMatches(
3487 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003488 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003489}
3490
3491TEST(IsExplicitTemplateSpecialization,
3492 DoesNotMatchExplicitTemplateInstantiations) {
3493 EXPECT_TRUE(notMatches(
3494 "template <typename T> class X {};"
3495 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003496 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003497 EXPECT_TRUE(notMatches(
3498 "template <typename T> void f(T t) {}"
3499 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003500 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003501}
3502
3503TEST(IsExplicitTemplateSpecialization,
3504 DoesNotMatchImplicitTemplateInstantiations) {
3505 EXPECT_TRUE(notMatches(
3506 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003507 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003508 EXPECT_TRUE(notMatches(
3509 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003510 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003511}
3512
3513TEST(IsExplicitTemplateSpecialization,
3514 MatchesExplicitTemplateSpecializations) {
3515 EXPECT_TRUE(matches(
3516 "template <typename T> class X {};"
3517 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003518 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003519 EXPECT_TRUE(matches(
3520 "template <typename T> void f(T t) {}"
3521 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003522 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003523}
3524
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003525TEST(HasAncenstor, MatchesDeclarationAncestors) {
3526 EXPECT_TRUE(matches(
3527 "class A { class B { class C {}; }; };",
3528 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3529}
3530
3531TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3532 EXPECT_TRUE(notMatches(
3533 "class A { class B { class C {}; }; };",
3534 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3535}
3536
3537TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3538 EXPECT_TRUE(matches(
3539 "class A { class B { void f() { C c; } class C {}; }; };",
3540 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3541 hasAncestor(recordDecl(hasName("A"))))))));
3542}
3543
3544TEST(HasAncenstor, MatchesStatementAncestors) {
3545 EXPECT_TRUE(matches(
3546 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003547 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003548}
3549
3550TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3551 EXPECT_TRUE(matches(
3552 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003553 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003554}
3555
3556TEST(HasAncestor, BindsRecursiveCombinations) {
3557 EXPECT_TRUE(matchAndVerifyResultTrue(
3558 "class C { class D { class E { class F { int y; }; }; }; };",
3559 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003560 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003561}
3562
3563TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3564 EXPECT_TRUE(matchAndVerifyResultTrue(
3565 "class C { class D { class E { class F { int y; }; }; }; };",
3566 fieldDecl(hasAncestor(
3567 decl(
3568 hasDescendant(recordDecl(isDefinition(),
3569 hasAncestor(recordDecl())))
3570 ).bind("d")
3571 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003572 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003573}
3574
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003575TEST(HasAncestor, MatchesClosestAncestor) {
3576 EXPECT_TRUE(matchAndVerifyResultTrue(
3577 "template <typename T> struct C {"
3578 " void f(int) {"
3579 " struct I { void g(T) { int x; } } i; i.g(42);"
3580 " }"
3581 "};"
3582 "template struct C<int>;",
3583 varDecl(hasName("x"),
3584 hasAncestor(functionDecl(hasParameter(
3585 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3586 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3587}
3588
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003589TEST(HasAncestor, MatchesInTemplateInstantiations) {
3590 EXPECT_TRUE(matches(
3591 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3592 "A<int>::B::C a;",
3593 fieldDecl(hasType(asString("int")),
3594 hasAncestor(recordDecl(hasName("A"))))));
3595}
3596
3597TEST(HasAncestor, MatchesInImplicitCode) {
3598 EXPECT_TRUE(matches(
3599 "struct X {}; struct A { A() {} X x; };",
3600 constructorDecl(
3601 hasAnyConstructorInitializer(withInitializer(expr(
3602 hasAncestor(recordDecl(hasName("A")))))))));
3603}
3604
Daniel Jasper632aea92012-10-22 16:26:51 +00003605TEST(HasParent, MatchesOnlyParent) {
3606 EXPECT_TRUE(matches(
3607 "void f() { if (true) { int x = 42; } }",
3608 compoundStmt(hasParent(ifStmt()))));
3609 EXPECT_TRUE(notMatches(
3610 "void f() { for (;;) { int x = 42; } }",
3611 compoundStmt(hasParent(ifStmt()))));
3612 EXPECT_TRUE(notMatches(
3613 "void f() { if (true) for (;;) { int x = 42; } }",
3614 compoundStmt(hasParent(ifStmt()))));
3615}
3616
Manuel Klimekc844a462012-12-06 14:42:48 +00003617TEST(HasAncestor, MatchesAllAncestors) {
3618 EXPECT_TRUE(matches(
3619 "template <typename T> struct C { static void f() { 42; } };"
3620 "void t() { C<int>::f(); }",
3621 integerLiteral(
3622 equals(42),
3623 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3624 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3625}
3626
3627TEST(HasParent, MatchesAllParents) {
3628 EXPECT_TRUE(matches(
3629 "template <typename T> struct C { static void f() { 42; } };"
3630 "void t() { C<int>::f(); }",
3631 integerLiteral(
3632 equals(42),
3633 hasParent(compoundStmt(hasParent(functionDecl(
3634 hasParent(recordDecl(isTemplateInstantiation())))))))));
3635 EXPECT_TRUE(matches(
3636 "template <typename T> struct C { static void f() { 42; } };"
3637 "void t() { C<int>::f(); }",
3638 integerLiteral(
3639 equals(42),
3640 hasParent(compoundStmt(hasParent(functionDecl(
3641 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3642 EXPECT_TRUE(matches(
3643 "template <typename T> struct C { static void f() { 42; } };"
3644 "void t() { C<int>::f(); }",
3645 integerLiteral(equals(42),
3646 hasParent(compoundStmt(allOf(
3647 hasParent(functionDecl(
3648 hasParent(recordDecl(isTemplateInstantiation())))),
3649 hasParent(functionDecl(hasParent(recordDecl(
3650 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003651 EXPECT_TRUE(
3652 notMatches("template <typename T> struct C { static void f() {} };"
3653 "void t() { C<int>::f(); }",
3654 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003655}
3656
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003657TEST(HasParent, NoDuplicateParents) {
3658 class HasDuplicateParents : public BoundNodesCallback {
3659 public:
3660 bool run(const BoundNodes *Nodes) override { return false; }
3661 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3662 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3663 std::set<const void *> Parents;
3664 for (const auto &Parent : Context->getParents(*Node)) {
3665 if (!Parents.insert(Parent.getMemoizationData()).second) {
3666 return true;
3667 }
3668 }
3669 return false;
3670 }
3671 };
3672 EXPECT_FALSE(matchAndVerifyResultTrue(
3673 "template <typename T> int Foo() { return 1 + 2; }\n"
3674 "int x = Foo<int>() + Foo<unsigned>();",
3675 stmt().bind("node"), new HasDuplicateParents()));
3676}
3677
Daniel Jasper516b02e2012-10-17 08:52:59 +00003678TEST(TypeMatching, MatchesTypes) {
3679 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3680}
3681
3682TEST(TypeMatching, MatchesArrayTypes) {
3683 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3684 EXPECT_TRUE(matches("int a[42];", arrayType()));
3685 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3686
3687 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3688 arrayType(hasElementType(builtinType()))));
3689
3690 EXPECT_TRUE(matches(
3691 "int const a[] = { 2, 3 };",
3692 qualType(arrayType(hasElementType(builtinType())))));
3693 EXPECT_TRUE(matches(
3694 "int const a[] = { 2, 3 };",
3695 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3696 EXPECT_TRUE(matches(
3697 "typedef const int T; T x[] = { 1, 2 };",
3698 qualType(isConstQualified(), arrayType())));
3699
3700 EXPECT_TRUE(notMatches(
3701 "int a[] = { 2, 3 };",
3702 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3703 EXPECT_TRUE(notMatches(
3704 "int a[] = { 2, 3 };",
3705 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3706 EXPECT_TRUE(notMatches(
3707 "int const a[] = { 2, 3 };",
3708 qualType(arrayType(hasElementType(builtinType())),
3709 unless(isConstQualified()))));
3710
3711 EXPECT_TRUE(matches("int a[2];",
3712 constantArrayType(hasElementType(builtinType()))));
3713 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3714}
3715
3716TEST(TypeMatching, MatchesComplexTypes) {
3717 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3718 EXPECT_TRUE(matches(
3719 "_Complex float f;",
3720 complexType(hasElementType(builtinType()))));
3721 EXPECT_TRUE(notMatches(
3722 "_Complex float f;",
3723 complexType(hasElementType(isInteger()))));
3724}
3725
3726TEST(TypeMatching, MatchesConstantArrayTypes) {
3727 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3728 EXPECT_TRUE(notMatches(
3729 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3730 constantArrayType(hasElementType(builtinType()))));
3731
3732 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3733 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3734 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3735}
3736
3737TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3738 EXPECT_TRUE(matches(
3739 "template <typename T, int Size> class array { T data[Size]; };",
3740 dependentSizedArrayType()));
3741 EXPECT_TRUE(notMatches(
3742 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3743 dependentSizedArrayType()));
3744}
3745
3746TEST(TypeMatching, MatchesIncompleteArrayType) {
3747 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3748 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3749
3750 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3751 incompleteArrayType()));
3752}
3753
3754TEST(TypeMatching, MatchesVariableArrayType) {
3755 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3756 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3757
3758 EXPECT_TRUE(matches(
3759 "void f(int b) { int a[b]; }",
3760 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3761 varDecl(hasName("b")))))))));
3762}
3763
3764TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003765 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3766 llvm::Triple::Win32) {
3767 // FIXME: Make this work for MSVC.
3768 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003769
David Majnemer197e2102014-03-05 06:32:38 +00003770 EXPECT_TRUE(matches("_Atomic(int) i;",
3771 atomicType(hasValueType(isInteger()))));
3772 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3773 atomicType(hasValueType(isInteger()))));
3774 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003775}
3776
3777TEST(TypeMatching, MatchesAutoTypes) {
3778 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3779 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3780 autoType()));
3781
Richard Smith061f1e22013-04-30 21:23:01 +00003782 // FIXME: Matching against the type-as-written can't work here, because the
3783 // type as written was not deduced.
3784 //EXPECT_TRUE(matches("auto a = 1;",
3785 // autoType(hasDeducedType(isInteger()))));
3786 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3787 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003788}
3789
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00003790TEST(TypeMatching, MatchesFunctionTypes) {
3791 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3792 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3793}
3794
Edwin Vaneec074802013-04-01 18:33:34 +00003795TEST(TypeMatching, MatchesParenType) {
3796 EXPECT_TRUE(
3797 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3798 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3799
3800 EXPECT_TRUE(matches(
3801 "int (*ptr_to_func)(int);",
3802 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3803 EXPECT_TRUE(notMatches(
3804 "int (*ptr_to_array)[4];",
3805 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3806}
3807
Daniel Jasper516b02e2012-10-17 08:52:59 +00003808TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003809 // FIXME: Reactive when these tests can be more specific (not matching
3810 // implicit code on certain platforms), likely when we have hasDescendant for
3811 // Types/TypeLocs.
3812 //EXPECT_TRUE(matchAndVerifyResultTrue(
3813 // "int* a;",
3814 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3815 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3816 //EXPECT_TRUE(matchAndVerifyResultTrue(
3817 // "int* a;",
3818 // pointerTypeLoc().bind("loc"),
3819 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003820 EXPECT_TRUE(matches(
3821 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003822 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003823 EXPECT_TRUE(matches(
3824 "int** a;",
3825 loc(pointerType(pointee(pointerType())))));
3826 EXPECT_TRUE(matches(
3827 "int* b; int* * const a = &b;",
3828 loc(qualType(isConstQualified(), pointerType()))));
3829
3830 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00003831 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3832 hasType(blockPointerType()))));
3833 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3834 hasType(memberPointerType()))));
3835 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3836 hasType(pointerType()))));
3837 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3838 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003839 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3840 hasType(lValueReferenceType()))));
3841 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3842 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003843
Daniel Jasper7943eb52012-10-17 13:35:36 +00003844 Fragment = "int *ptr;";
3845 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3846 hasType(blockPointerType()))));
3847 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3848 hasType(memberPointerType()))));
3849 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3850 hasType(pointerType()))));
3851 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3852 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003853
Daniel Jasper7943eb52012-10-17 13:35:36 +00003854 Fragment = "int a; int &ref = a;";
3855 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3856 hasType(blockPointerType()))));
3857 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3858 hasType(memberPointerType()))));
3859 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3860 hasType(pointerType()))));
3861 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3862 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003863 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3864 hasType(lValueReferenceType()))));
3865 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3866 hasType(rValueReferenceType()))));
3867
3868 Fragment = "int &&ref = 2;";
3869 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3870 hasType(blockPointerType()))));
3871 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3872 hasType(memberPointerType()))));
3873 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3874 hasType(pointerType()))));
3875 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3876 hasType(referenceType()))));
3877 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3878 hasType(lValueReferenceType()))));
3879 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3880 hasType(rValueReferenceType()))));
3881}
3882
3883TEST(TypeMatching, AutoRefTypes) {
3884 std::string Fragment = "auto a = 1;"
3885 "auto b = a;"
3886 "auto &c = a;"
3887 "auto &&d = c;"
3888 "auto &&e = 2;";
3889 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
3890 hasType(referenceType()))));
3891 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
3892 hasType(referenceType()))));
3893 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3894 hasType(referenceType()))));
3895 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3896 hasType(lValueReferenceType()))));
3897 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
3898 hasType(rValueReferenceType()))));
3899 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3900 hasType(referenceType()))));
3901 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3902 hasType(lValueReferenceType()))));
3903 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
3904 hasType(rValueReferenceType()))));
3905 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3906 hasType(referenceType()))));
3907 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
3908 hasType(lValueReferenceType()))));
3909 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3910 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003911}
3912
3913TEST(TypeMatching, PointeeTypes) {
3914 EXPECT_TRUE(matches("int b; int &a = b;",
3915 referenceType(pointee(builtinType()))));
3916 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
3917
3918 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003919 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003920
3921 EXPECT_TRUE(matches(
3922 "int const *A;",
3923 pointerType(pointee(isConstQualified(), builtinType()))));
3924 EXPECT_TRUE(notMatches(
3925 "int *A;",
3926 pointerType(pointee(isConstQualified(), builtinType()))));
3927}
3928
3929TEST(TypeMatching, MatchesPointersToConstTypes) {
3930 EXPECT_TRUE(matches("int b; int * const a = &b;",
3931 loc(pointerType())));
3932 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00003933 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003934 EXPECT_TRUE(matches(
3935 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00003936 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003937 EXPECT_TRUE(matches(
3938 "int b; const int * a = &b;",
3939 pointerType(pointee(builtinType()))));
3940}
3941
3942TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003943 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
3944 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003945}
3946
Edwin Vanef901b712013-02-25 14:49:29 +00003947TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00003948 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00003949 templateSpecializationType()));
3950}
3951
Edwin Vaneb6eae142013-02-25 20:43:32 +00003952TEST(TypeMatching, MatchesRecordType) {
3953 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00003954 EXPECT_TRUE(matches("struct S{}; S s;",
3955 recordType(hasDeclaration(recordDecl(hasName("S"))))));
3956 EXPECT_TRUE(notMatches("int i;",
3957 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00003958}
3959
3960TEST(TypeMatching, MatchesElaboratedType) {
3961 EXPECT_TRUE(matches(
3962 "namespace N {"
3963 " namespace M {"
3964 " class D {};"
3965 " }"
3966 "}"
3967 "N::M::D d;", elaboratedType()));
3968 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
3969 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
3970}
3971
3972TEST(ElaboratedTypeNarrowing, hasQualifier) {
3973 EXPECT_TRUE(matches(
3974 "namespace N {"
3975 " namespace M {"
3976 " class D {};"
3977 " }"
3978 "}"
3979 "N::M::D d;",
3980 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
3981 EXPECT_TRUE(notMatches(
3982 "namespace M {"
3983 " class D {};"
3984 "}"
3985 "M::D d;",
3986 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00003987 EXPECT_TRUE(notMatches(
3988 "struct D {"
3989 "} d;",
3990 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00003991}
3992
3993TEST(ElaboratedTypeNarrowing, namesType) {
3994 EXPECT_TRUE(matches(
3995 "namespace N {"
3996 " namespace M {"
3997 " class D {};"
3998 " }"
3999 "}"
4000 "N::M::D d;",
4001 elaboratedType(elaboratedType(namesType(recordType(
4002 hasDeclaration(namedDecl(hasName("D")))))))));
4003 EXPECT_TRUE(notMatches(
4004 "namespace M {"
4005 " class D {};"
4006 "}"
4007 "M::D d;",
4008 elaboratedType(elaboratedType(namesType(typedefType())))));
4009}
4010
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004011TEST(NNS, MatchesNestedNameSpecifiers) {
4012 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4013 nestedNameSpecifier()));
4014 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4015 nestedNameSpecifier()));
4016 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4017 nestedNameSpecifier()));
4018
4019 EXPECT_TRUE(matches(
4020 "struct A { static void f() {} }; void g() { A::f(); }",
4021 nestedNameSpecifier()));
4022 EXPECT_TRUE(notMatches(
4023 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4024 nestedNameSpecifier()));
4025}
4026
Daniel Jasper87c3d362012-09-20 14:12:57 +00004027TEST(NullStatement, SimpleCases) {
4028 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4029 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4030}
4031
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004032TEST(NNS, MatchesTypes) {
4033 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4034 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4035 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4036 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4037 Matcher));
4038 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4039}
4040
4041TEST(NNS, MatchesNamespaceDecls) {
4042 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4043 specifiesNamespace(hasName("ns")));
4044 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4045 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4046 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4047}
4048
4049TEST(NNS, BindsNestedNameSpecifiers) {
4050 EXPECT_TRUE(matchAndVerifyResultTrue(
4051 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4052 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4053 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4054}
4055
4056TEST(NNS, BindsNestedNameSpecifierLocs) {
4057 EXPECT_TRUE(matchAndVerifyResultTrue(
4058 "namespace ns { struct B {}; } ns::B b;",
4059 loc(nestedNameSpecifier()).bind("loc"),
4060 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4061}
4062
4063TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4064 EXPECT_TRUE(matches(
4065 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4066 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4067 EXPECT_TRUE(matches(
4068 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004069 nestedNameSpecifierLoc(hasPrefix(
4070 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004071}
4072
Daniel Jasper6fc34332012-10-30 15:42:00 +00004073TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4074 std::string Fragment =
4075 "namespace a { struct A { struct B { struct C {}; }; }; };"
4076 "void f() { a::A::B::C c; }";
4077 EXPECT_TRUE(matches(
4078 Fragment,
4079 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4080 hasDescendant(nestedNameSpecifier(
4081 specifiesNamespace(hasName("a")))))));
4082 EXPECT_TRUE(notMatches(
4083 Fragment,
4084 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4085 has(nestedNameSpecifier(
4086 specifiesNamespace(hasName("a")))))));
4087 EXPECT_TRUE(matches(
4088 Fragment,
4089 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4090 has(nestedNameSpecifier(
4091 specifiesNamespace(hasName("a")))))));
4092
4093 // Not really useful because a NestedNameSpecifier can af at most one child,
4094 // but to complete the interface.
4095 EXPECT_TRUE(matchAndVerifyResultTrue(
4096 Fragment,
4097 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4098 forEach(nestedNameSpecifier().bind("x"))),
4099 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4100}
4101
4102TEST(NNS, NestedNameSpecifiersAsDescendants) {
4103 std::string Fragment =
4104 "namespace a { struct A { struct B { struct C {}; }; }; };"
4105 "void f() { a::A::B::C c; }";
4106 EXPECT_TRUE(matches(
4107 Fragment,
4108 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4109 asString("struct a::A")))))));
4110 EXPECT_TRUE(matchAndVerifyResultTrue(
4111 Fragment,
4112 functionDecl(hasName("f"),
4113 forEachDescendant(nestedNameSpecifier().bind("x"))),
4114 // Nested names: a, a::A and a::A::B.
4115 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4116}
4117
4118TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4119 std::string Fragment =
4120 "namespace a { struct A { struct B { struct C {}; }; }; };"
4121 "void f() { a::A::B::C c; }";
4122 EXPECT_TRUE(matches(
4123 Fragment,
4124 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4125 hasDescendant(loc(nestedNameSpecifier(
4126 specifiesNamespace(hasName("a"))))))));
4127 EXPECT_TRUE(notMatches(
4128 Fragment,
4129 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4130 has(loc(nestedNameSpecifier(
4131 specifiesNamespace(hasName("a"))))))));
4132 EXPECT_TRUE(matches(
4133 Fragment,
4134 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4135 has(loc(nestedNameSpecifier(
4136 specifiesNamespace(hasName("a"))))))));
4137
4138 EXPECT_TRUE(matchAndVerifyResultTrue(
4139 Fragment,
4140 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4141 forEach(nestedNameSpecifierLoc().bind("x"))),
4142 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4143}
4144
4145TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4146 std::string Fragment =
4147 "namespace a { struct A { struct B { struct C {}; }; }; };"
4148 "void f() { a::A::B::C c; }";
4149 EXPECT_TRUE(matches(
4150 Fragment,
4151 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4152 asString("struct a::A"))))))));
4153 EXPECT_TRUE(matchAndVerifyResultTrue(
4154 Fragment,
4155 functionDecl(hasName("f"),
4156 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4157 // Nested names: a, a::A and a::A::B.
4158 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4159}
4160
Manuel Klimek191c0932013-02-01 13:41:35 +00004161template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004162public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004163 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4164 StringRef InnerId)
4165 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004166 }
4167
Manuel Klimek191c0932013-02-01 13:41:35 +00004168 virtual bool run(const BoundNodes *Nodes) { return false; }
4169
Manuel Klimekc2687452012-10-24 14:47:44 +00004170 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4171 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004172 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4173 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004174 }
4175private:
4176 std::string Id;
4177 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004178 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004179};
4180
4181TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004182 EXPECT_TRUE(matchAndVerifyResultTrue(
4183 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4184 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004185 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4186 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004187 EXPECT_TRUE(matchAndVerifyResultFalse(
4188 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4189 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004190 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4191 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004192}
4193
4194TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004195 EXPECT_TRUE(matchAndVerifyResultTrue(
4196 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004197 new VerifyMatchOnNode<clang::Stmt>(
4198 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004199 EXPECT_TRUE(matchAndVerifyResultFalse(
4200 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004201 new VerifyMatchOnNode<clang::Stmt>(
4202 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004203}
4204
4205TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4206 EXPECT_TRUE(matchAndVerifyResultTrue(
4207 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4208 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004209 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004210 EXPECT_TRUE(matchAndVerifyResultFalse(
4211 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4212 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004213 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004214}
4215
Manuel Klimekbee08572013-02-07 12:42:10 +00004216template <typename T>
4217class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4218public:
4219 virtual bool run(const BoundNodes *Nodes) { return false; }
4220
4221 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4222 const T *Node = Nodes->getNodeAs<T>("");
4223 return verify(*Nodes, *Context, Node);
4224 }
4225
4226 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004227 // Use the original typed pointer to verify we can pass pointers to subtypes
4228 // to equalsNode.
4229 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004230 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004231 "", match(stmt(hasParent(
4232 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004233 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004234 }
4235 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004236 // Use the original typed pointer to verify we can pass pointers to subtypes
4237 // to equalsNode.
4238 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004239 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004240 "", match(decl(hasParent(
4241 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004242 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004243 }
4244};
4245
4246TEST(IsEqualTo, MatchesNodesByIdentity) {
4247 EXPECT_TRUE(matchAndVerifyResultTrue(
4248 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004249 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4250 EXPECT_TRUE(matchAndVerifyResultTrue(
4251 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4252 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004253}
4254
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004255class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4256public:
4257 VerifyStartOfTranslationUnit() : Called(false) {}
4258 virtual void run(const MatchFinder::MatchResult &Result) {
4259 EXPECT_TRUE(Called);
4260 }
4261 virtual void onStartOfTranslationUnit() {
4262 Called = true;
4263 }
4264 bool Called;
4265};
4266
4267TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4268 MatchFinder Finder;
4269 VerifyStartOfTranslationUnit VerifyCallback;
4270 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004271 std::unique_ptr<FrontendActionFactory> Factory(
4272 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004273 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4274 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004275
4276 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004277 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004278 ASSERT_TRUE(AST.get());
4279 Finder.matchAST(AST->getASTContext());
4280 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004281}
4282
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004283class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4284public:
4285 VerifyEndOfTranslationUnit() : Called(false) {}
4286 virtual void run(const MatchFinder::MatchResult &Result) {
4287 EXPECT_FALSE(Called);
4288 }
4289 virtual void onEndOfTranslationUnit() {
4290 Called = true;
4291 }
4292 bool Called;
4293};
4294
4295TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4296 MatchFinder Finder;
4297 VerifyEndOfTranslationUnit VerifyCallback;
4298 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004299 std::unique_ptr<FrontendActionFactory> Factory(
4300 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004301 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4302 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004303
4304 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004305 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004306 ASSERT_TRUE(AST.get());
4307 Finder.matchAST(AST->getASTContext());
4308 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004309}
4310
Manuel Klimekbbb75852013-06-20 14:06:32 +00004311TEST(EqualsBoundNodeMatcher, QualType) {
4312 EXPECT_TRUE(matches(
4313 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4314 hasInitializer(ignoringParenImpCasts(
4315 hasType(qualType(equalsBoundNode("type"))))))));
4316 EXPECT_TRUE(notMatches("int i = 1.f;",
4317 varDecl(hasType(qualType().bind("type")),
4318 hasInitializer(ignoringParenImpCasts(hasType(
4319 qualType(equalsBoundNode("type"))))))));
4320}
4321
4322TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4323 EXPECT_TRUE(notMatches(
4324 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4325 hasInitializer(ignoringParenImpCasts(
4326 hasType(qualType(equalsBoundNode("type"))))))));
4327}
4328
4329TEST(EqualsBoundNodeMatcher, Stmt) {
4330 EXPECT_TRUE(
4331 matches("void f() { if(true) {} }",
4332 stmt(allOf(ifStmt().bind("if"),
4333 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4334
4335 EXPECT_TRUE(notMatches(
4336 "void f() { if(true) { if (true) {} } }",
4337 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4338}
4339
4340TEST(EqualsBoundNodeMatcher, Decl) {
4341 EXPECT_TRUE(matches(
4342 "class X { class Y {}; };",
4343 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4344 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4345
4346 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4347 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4348 has(decl(equalsBoundNode("record")))))));
4349}
4350
4351TEST(EqualsBoundNodeMatcher, Type) {
4352 EXPECT_TRUE(matches(
4353 "class X { int a; int b; };",
4354 recordDecl(
4355 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4356 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4357
4358 EXPECT_TRUE(notMatches(
4359 "class X { int a; double b; };",
4360 recordDecl(
4361 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4362 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4363}
4364
4365TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004366 EXPECT_TRUE(matchAndVerifyResultTrue(
4367 "int f() {"
4368 " if (1) {"
4369 " int i = 9;"
4370 " }"
4371 " int j = 10;"
4372 " {"
4373 " float k = 9.0;"
4374 " }"
4375 " return 0;"
4376 "}",
4377 // Look for variable declarations within functions whose type is the same
4378 // as the function return type.
4379 functionDecl(returns(qualType().bind("type")),
4380 forEachDescendant(varDecl(hasType(
4381 qualType(equalsBoundNode("type")))).bind("decl"))),
4382 // Only i and j should match, not k.
4383 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4384}
4385
4386TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4387 EXPECT_TRUE(matchAndVerifyResultTrue(
4388 "void f() {"
4389 " int x;"
4390 " double d;"
4391 " x = d + x - d + x;"
4392 "}",
4393 functionDecl(
4394 hasName("f"), forEachDescendant(varDecl().bind("d")),
4395 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4396 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4397}
4398
Manuel Klimekce68f772014-03-25 14:39:26 +00004399TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4400 EXPECT_TRUE(matchAndVerifyResultTrue(
4401 "struct StringRef { int size() const; const char* data() const; };"
4402 "void f(StringRef v) {"
4403 " v.data();"
4404 "}",
4405 memberCallExpr(
4406 callee(methodDecl(hasName("data"))),
4407 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4408 .bind("var")))),
4409 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4410 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4411 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4412 .bind("data"),
4413 new VerifyIdIsBoundTo<Expr>("data", 1)));
4414
4415 EXPECT_FALSE(matches(
4416 "struct StringRef { int size() const; const char* data() const; };"
4417 "void f(StringRef v) {"
4418 " v.data();"
4419 " v.size();"
4420 "}",
4421 memberCallExpr(
4422 callee(methodDecl(hasName("data"))),
4423 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4424 .bind("var")))),
4425 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4426 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4427 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4428 .bind("data")));
4429}
4430
Manuel Klimek04616e42012-07-06 05:48:52 +00004431} // end namespace ast_matchers
4432} // end namespace clang