blob: 4eb4c0d6727de438bc1f55310c1ebb971d0bb941 [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
Manuel Klimek94ad0bf2014-09-04 08:51:06 +0000380TEST(DeclarationMatcher, LinkageSpecification) {
381 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
382 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
383}
384
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000385TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000386 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000387 EXPECT_TRUE(notMatches("class X;", ClassX));
388 EXPECT_TRUE(notMatches("class X {};", ClassX));
389}
390
391TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000392 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000393 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
394 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
395}
396
397TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
398 EXPECT_TRUE(notMatches("template<typename T> class X { };"
399 "template<> class X<int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000400 classTemplateDecl(hasName("X"),
401 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000402}
403
404TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
405 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
406 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000407 classTemplateDecl(hasName("X"),
408 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000409}
410
Daniel Jasper4e566c42012-07-12 08:50:38 +0000411TEST(AllOf, AllOverloadsWork) {
412 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000413 "struct T { };"
414 "int f(int, T*, int, int);"
415 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000416 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000417 callExpr(allOf(callee(functionDecl(hasName("f"))),
418 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000419 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000420 callExpr(allOf(callee(functionDecl(hasName("f"))),
421 hasArgument(0, declRefExpr(to(varDecl()))),
422 hasArgument(1, hasType(pointsTo(
423 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000424 EXPECT_TRUE(matches(Program,
425 callExpr(allOf(callee(functionDecl(hasName("f"))),
426 hasArgument(0, declRefExpr(to(varDecl()))),
427 hasArgument(1, hasType(pointsTo(
428 recordDecl(hasName("T"))))),
429 hasArgument(2, integerLiteral(equals(3)))))));
430 EXPECT_TRUE(matches(Program,
431 callExpr(allOf(callee(functionDecl(hasName("f"))),
432 hasArgument(0, declRefExpr(to(varDecl()))),
433 hasArgument(1, hasType(pointsTo(
434 recordDecl(hasName("T"))))),
435 hasArgument(2, integerLiteral(equals(3))),
436 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000437}
438
Manuel Klimek04616e42012-07-06 05:48:52 +0000439TEST(DeclarationMatcher, MatchAnyOf) {
440 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000441 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000442 EXPECT_TRUE(
443 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
444 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
445 EXPECT_TRUE(
446 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
447 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
448
Daniel Jasper84c763e2012-07-15 19:57:12 +0000449 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000450 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000451 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
452 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
453
Manuel Klimek04616e42012-07-06 05:48:52 +0000454 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000455 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
456 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000457 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
458 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
459 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
460 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
461 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
462 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
463}
464
465TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000466 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000467 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
468 EXPECT_TRUE(matches("class X {};", HasClassX));
469
470 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000471 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000472 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
473 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
474 EXPECT_TRUE(
475 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
476}
477
478TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
479 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000480 recordDecl(
481 has(recordDecl(
482 has(recordDecl(hasName("X"))),
483 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000484 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000485 has(recordDecl(
486 has(recordDecl(hasName("A"))),
487 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000488 hasName("C"))),
489 hasName("F"));
490
491 EXPECT_TRUE(matches(
492 "class F {"
493 " class Z {"
494 " class X {};"
495 " class Y {};"
496 " };"
497 " class C {"
498 " class A {};"
499 " class B {};"
500 " };"
501 "};", Recursive));
502
503 EXPECT_TRUE(matches(
504 "class F {"
505 " class Z {"
506 " class A {};"
507 " class X {};"
508 " class Y {};"
509 " };"
510 " class C {"
511 " class X {};"
512 " class A {};"
513 " class B {};"
514 " };"
515 "};", Recursive));
516
517 EXPECT_TRUE(matches(
518 "class O1 {"
519 " class O2 {"
520 " class F {"
521 " class Z {"
522 " class A {};"
523 " class X {};"
524 " class Y {};"
525 " };"
526 " class C {"
527 " class X {};"
528 " class A {};"
529 " class B {};"
530 " };"
531 " };"
532 " };"
533 "};", Recursive));
534}
535
536TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
537 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000538 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000539 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000540 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000541 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000542 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000543 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000544 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000545 hasName("Y"))),
546 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000547 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000548 anyOf(
549 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000550 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000551 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000552 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000553 hasName("B")))))),
554 hasName("F")));
555
556 EXPECT_TRUE(matches("class F {};", Recursive));
557 EXPECT_TRUE(matches("class Z {};", Recursive));
558 EXPECT_TRUE(matches("class C {};", Recursive));
559 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
560 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
561 EXPECT_TRUE(
562 matches("class O1 { class O2 {"
563 " class M { class N { class B {}; }; }; "
564 "}; };", Recursive));
565}
566
567TEST(DeclarationMatcher, MatchNot) {
568 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000569 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000570 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000571 unless(hasName("X")));
572 EXPECT_TRUE(notMatches("", NotClassX));
573 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
574 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
575 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
576 EXPECT_TRUE(
577 notMatches("class Y {}; class Z {}; class X : public Y {};",
578 NotClassX));
579
580 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000581 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000582 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000583 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000584 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000585 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000586 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
587 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
588 ClassXHasNotClassY));
589}
590
591TEST(DeclarationMatcher, HasDescendant) {
592 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000593 recordDecl(
594 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000595 hasName("Z"));
596 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
597 EXPECT_TRUE(
598 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
599 EXPECT_TRUE(
600 matches("class Z { class A { class Y { class X {}; }; }; };",
601 ZDescendantClassX));
602 EXPECT_TRUE(
603 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
604 ZDescendantClassX));
605 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
606
607 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000608 recordDecl(
609 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000610 hasName("X"))),
611 hasName("Z"));
612 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
613 ZDescendantClassXHasClassY));
614 EXPECT_TRUE(
615 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
616 ZDescendantClassXHasClassY));
617 EXPECT_TRUE(notMatches(
618 "class Z {"
619 " class A {"
620 " class B {"
621 " class X {"
622 " class C {"
623 " class Y {};"
624 " };"
625 " };"
626 " }; "
627 " };"
628 "};", ZDescendantClassXHasClassY));
629
630 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000631 recordDecl(
632 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
633 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000634 hasName("Z"));
635 EXPECT_TRUE(
636 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
637 ZDescendantClassXDescendantClassY));
638 EXPECT_TRUE(matches(
639 "class Z {"
640 " class A {"
641 " class X {"
642 " class B {"
643 " class Y {};"
644 " };"
645 " class Y {};"
646 " };"
647 " };"
648 "};", ZDescendantClassXDescendantClassY));
649}
650
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000651TEST(DeclarationMatcher, HasDescendantMemoization) {
652 DeclarationMatcher CannotMemoize =
653 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
654 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
655}
656
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000657TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
658 auto Name = hasName("i");
659 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
660 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
661 // Matching VD first should not make a cache hit for RD.
662 EXPECT_TRUE(notMatches("void f() { int i; }",
663 decl(hasDescendant(VD), hasDescendant(RD))));
664 EXPECT_TRUE(notMatches("void f() { int i; }",
665 decl(hasDescendant(RD), hasDescendant(VD))));
666 // Not matching RD first should not make a cache hit for VD either.
667 EXPECT_TRUE(matches("void f() { int i; }",
668 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
669}
670
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000671TEST(DeclarationMatcher, HasAttr) {
672 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
673 decl(hasAttr(clang::attr::WarnUnused))));
674 EXPECT_FALSE(matches("struct X {};",
675 decl(hasAttr(clang::attr::WarnUnused))));
676}
677
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000678TEST(DeclarationMatcher, MatchCudaDecl) {
679 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
680 "void g() { f<<<1, 2>>>(); }",
681 CUDAKernelCallExpr()));
682 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000683 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000684 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000685 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000686 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000687 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000688}
689
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000690// Implements a run method that returns whether BoundNodes contains a
691// Decl bound to Id that can be dynamically cast to T.
692// Optionally checks that the check succeeded a specific number of times.
693template <typename T>
694class VerifyIdIsBoundTo : public BoundNodesCallback {
695public:
696 // Create an object that checks that a node of type \c T was bound to \c Id.
697 // Does not check for a certain number of matches.
698 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
699 : Id(Id), ExpectedCount(-1), Count(0) {}
700
701 // Create an object that checks that a node of type \c T was bound to \c Id.
702 // Checks that there were exactly \c ExpectedCount matches.
703 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
704 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
705
706 // Create an object that checks that a node of type \c T was bound to \c Id.
707 // Checks that there was exactly one match with the name \c ExpectedName.
708 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000709 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
710 int ExpectedCount = 1)
711 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
712 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000713
Craig Toppera798a9d2014-03-02 09:32:10 +0000714 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000715 if (ExpectedCount != -1)
716 EXPECT_EQ(ExpectedCount, Count);
717 if (!ExpectedName.empty())
718 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000719 Count = 0;
720 Name.clear();
721 }
722
723 ~VerifyIdIsBoundTo() {
724 EXPECT_EQ(0, Count);
725 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000726 }
727
Fariborz Jahanian5afc8692014-10-01 16:56:40 +0000728 virtual bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000729 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000730 if (Nodes->getNodeAs<T>(Id)) {
731 ++Count;
732 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
733 Name = Named->getNameAsString();
734 } else if (const NestedNameSpecifier *NNS =
735 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
736 llvm::raw_string_ostream OS(Name);
737 NNS->print(OS, PrintingPolicy(LangOptions()));
738 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000739 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
740 EXPECT_NE(M.end(), I);
741 if (I != M.end())
742 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000743 return true;
744 }
Craig Topper416fa342014-06-08 08:38:12 +0000745 EXPECT_TRUE(M.count(Id) == 0 ||
746 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000747 return false;
748 }
749
Fariborz Jahanian5afc8692014-10-01 16:56:40 +0000750 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000751 return run(Nodes);
752 }
753
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000754private:
755 const std::string Id;
756 const int ExpectedCount;
757 int Count;
758 const std::string ExpectedName;
759 std::string Name;
760};
761
762TEST(HasDescendant, MatchesDescendantTypes) {
763 EXPECT_TRUE(matches("void f() { int i = 3; }",
764 decl(hasDescendant(loc(builtinType())))));
765 EXPECT_TRUE(matches("void f() { int i = 3; }",
766 stmt(hasDescendant(builtinType()))));
767
768 EXPECT_TRUE(matches("void f() { int i = 3; }",
769 stmt(hasDescendant(loc(builtinType())))));
770 EXPECT_TRUE(matches("void f() { int i = 3; }",
771 stmt(hasDescendant(qualType(builtinType())))));
772
773 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
774 stmt(hasDescendant(isInteger()))));
775
776 EXPECT_TRUE(matchAndVerifyResultTrue(
777 "void f() { int a; float c; int d; int e; }",
778 functionDecl(forEachDescendant(
779 varDecl(hasDescendant(isInteger())).bind("x"))),
780 new VerifyIdIsBoundTo<Decl>("x", 3)));
781}
782
783TEST(HasDescendant, MatchesDescendantsOfTypes) {
784 EXPECT_TRUE(matches("void f() { int*** i; }",
785 qualType(hasDescendant(builtinType()))));
786 EXPECT_TRUE(matches("void f() { int*** i; }",
787 qualType(hasDescendant(
788 pointerType(pointee(builtinType()))))));
789 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000790 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000791
792 EXPECT_TRUE(matchAndVerifyResultTrue(
793 "void f() { int*** i; }",
794 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
795 new VerifyIdIsBoundTo<Type>("x", 2)));
796}
797
798TEST(Has, MatchesChildrenOfTypes) {
799 EXPECT_TRUE(matches("int i;",
800 varDecl(hasName("i"), has(isInteger()))));
801 EXPECT_TRUE(notMatches("int** i;",
802 varDecl(hasName("i"), has(isInteger()))));
803 EXPECT_TRUE(matchAndVerifyResultTrue(
804 "int (*f)(float, int);",
805 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
806 new VerifyIdIsBoundTo<QualType>("x", 2)));
807}
808
809TEST(Has, MatchesChildTypes) {
810 EXPECT_TRUE(matches(
811 "int* i;",
812 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
813 EXPECT_TRUE(notMatches(
814 "int* i;",
815 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
816}
817
Daniel Jasper1dad1832012-07-10 20:20:19 +0000818TEST(Enum, DoesNotMatchClasses) {
819 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
820}
821
822TEST(Enum, MatchesEnums) {
823 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
824}
825
826TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000827 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000828 EXPECT_TRUE(matches("enum X{ A };", Matcher));
829 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
830 EXPECT_TRUE(notMatches("enum X {};", Matcher));
831}
832
Manuel Klimek04616e42012-07-06 05:48:52 +0000833TEST(StatementMatcher, Has) {
834 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000835 expr(hasType(pointsTo(recordDecl(hasName("X")))),
836 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000837
838 EXPECT_TRUE(matches(
839 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
840 EXPECT_TRUE(notMatches(
841 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
842}
843
844TEST(StatementMatcher, HasDescendant) {
845 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000846 expr(hasType(pointsTo(recordDecl(hasName("X")))),
847 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000848
849 EXPECT_TRUE(matches(
850 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
851 HasDescendantVariableI));
852 EXPECT_TRUE(notMatches(
853 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
854 HasDescendantVariableI));
855}
856
857TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000858 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000859
860 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
861 EXPECT_TRUE(notMatches("class A {};", TypeA));
862
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000863 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000864
865 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
866 TypeDerivedFromA));
867 EXPECT_TRUE(notMatches("class A {};", TypeA));
868
869 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000870 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000871
872 EXPECT_TRUE(
873 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
874}
875
Manuel Klimek04616e42012-07-06 05:48:52 +0000876TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000877 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000878
879 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000880 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000881
882 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000883 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000884
885 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000886 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000887
888 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
889 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000890 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000891
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000892 StatementMatcher MethodX =
893 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000894
895 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
896 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000897 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000898}
899
900TEST(Matcher, BindTheSameNameInAlternatives) {
901 StatementMatcher matcher = anyOf(
902 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000903 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000904 hasRHS(integerLiteral(equals(0)))),
905 binaryOperator(hasOperatorName("+"),
906 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000907 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000908
909 EXPECT_TRUE(matchAndVerifyResultTrue(
910 // The first branch of the matcher binds x to 0 but then fails.
911 // The second branch binds x to f() and succeeds.
912 "int f() { return 0 + f(); }",
913 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000914 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000915}
916
Manuel Klimekfdf98762012-08-30 19:41:06 +0000917TEST(Matcher, BindsIDForMemoizedResults) {
918 // Using the same matcher in two match expressions will make memoization
919 // kick in.
920 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
921 EXPECT_TRUE(matchAndVerifyResultTrue(
922 "class A { class B { class X {}; }; };",
923 DeclarationMatcher(anyOf(
924 recordDecl(hasName("A"), hasDescendant(ClassX)),
925 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000926 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000927}
928
Daniel Jasper856194d02012-12-03 15:43:25 +0000929TEST(HasDeclaration, HasDeclarationOfEnumType) {
930 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
931 expr(hasType(pointsTo(
932 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
933}
934
Edwin Vaneed936452013-02-25 14:32:42 +0000935TEST(HasDeclaration, HasGetDeclTraitTest) {
936 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
937 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
938 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
939}
940
Edwin Vane2c197e02013-02-19 17:14:34 +0000941TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
942 EXPECT_TRUE(matches("typedef int X; X a;",
943 varDecl(hasName("a"),
944 hasType(typedefType(hasDeclaration(decl()))))));
945
946 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
947}
948
Edwin Vanef901b712013-02-25 14:49:29 +0000949TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
950 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
951 varDecl(hasType(templateSpecializationType(
952 hasDeclaration(namedDecl(hasName("A"))))))));
953}
954
Manuel Klimek04616e42012-07-06 05:48:52 +0000955TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000956 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000957 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000958 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000959 EXPECT_TRUE(
960 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000961 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000962 EXPECT_TRUE(
963 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000964 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000965}
966
967TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000968 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000969 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000970 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000971 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000972 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000973 EXPECT_TRUE(
974 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000975 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000976}
977
978TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000979 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000980 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000981 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000982 EXPECT_TRUE(
983 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000984 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000985}
986
987TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000988 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000989 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000990 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000991 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000992 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000993}
994
Manuel Klimekc16c6522013-06-20 13:08:29 +0000995TEST(HasTypeLoc, MatchesDeclaratorDecls) {
996 EXPECT_TRUE(matches("int x;",
997 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
998
999 // Make sure we don't crash on implicit constructors.
1000 EXPECT_TRUE(notMatches("class X {}; X x;",
1001 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1002}
1003
Manuel Klimek04616e42012-07-06 05:48:52 +00001004TEST(Matcher, Call) {
1005 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001006 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001007 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001008
1009 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1010 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1011
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001012 StatementMatcher MethodOnY =
1013 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001014
1015 EXPECT_TRUE(
1016 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1017 MethodOnY));
1018 EXPECT_TRUE(
1019 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1020 MethodOnY));
1021 EXPECT_TRUE(
1022 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1023 MethodOnY));
1024 EXPECT_TRUE(
1025 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1026 MethodOnY));
1027 EXPECT_TRUE(
1028 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1029 MethodOnY));
1030
1031 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001032 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001033
1034 EXPECT_TRUE(
1035 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1036 MethodOnYPointer));
1037 EXPECT_TRUE(
1038 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1039 MethodOnYPointer));
1040 EXPECT_TRUE(
1041 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1042 MethodOnYPointer));
1043 EXPECT_TRUE(
1044 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1045 MethodOnYPointer));
1046 EXPECT_TRUE(
1047 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1048 MethodOnYPointer));
1049}
1050
Daniel Jasper5901e472012-10-01 13:40:41 +00001051TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001052 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001053 lambdaExpr()));
1054}
1055
1056TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001057 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1058 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001059 forRangeStmt()));
1060 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1061 forRangeStmt()));
1062}
1063
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001064TEST(Matcher, SubstNonTypeTemplateParm) {
1065 EXPECT_FALSE(matches("template<int N>\n"
1066 "struct A { static const int n = 0; };\n"
1067 "struct B : public A<42> {};",
1068 substNonTypeTemplateParmExpr()));
1069 EXPECT_TRUE(matches("template<int N>\n"
1070 "struct A { static const int n = N; };\n"
1071 "struct B : public A<42> {};",
1072 substNonTypeTemplateParmExpr()));
1073}
1074
Daniel Jasper5901e472012-10-01 13:40:41 +00001075TEST(Matcher, UserDefinedLiteral) {
1076 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1077 " return i + 1;"
1078 "}"
1079 "char c = 'a'_inc;",
1080 userDefinedLiteral()));
1081}
1082
Daniel Jasper87c3d362012-09-20 14:12:57 +00001083TEST(Matcher, FlowControl) {
1084 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1085 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1086 continueStmt()));
1087 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1088 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1089 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1090}
1091
Daniel Jasper1dad1832012-07-10 20:20:19 +00001092TEST(HasType, MatchesAsString) {
1093 EXPECT_TRUE(
1094 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001095 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001096 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001097 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001098 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001099 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001100 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001101 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001102}
1103
Manuel Klimek04616e42012-07-06 05:48:52 +00001104TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001105 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001106 // Unary operator
1107 EXPECT_TRUE(matches("class Y { }; "
1108 "bool operator!(Y x) { return false; }; "
1109 "Y y; bool c = !y;", OpCall));
1110 // No match -- special operators like "new", "delete"
1111 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1112 // we need to figure out include paths in the test.
1113 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1114 // "class Y { }; "
1115 // "void *operator new(size_t size) { return 0; } "
1116 // "Y *y = new Y;", OpCall));
1117 EXPECT_TRUE(notMatches("class Y { }; "
1118 "void operator delete(void *p) { } "
1119 "void a() {Y *y = new Y; delete y;}", OpCall));
1120 // Binary operator
1121 EXPECT_TRUE(matches("class Y { }; "
1122 "bool operator&&(Y x, Y y) { return true; }; "
1123 "Y a; Y b; bool c = a && b;",
1124 OpCall));
1125 // No match -- normal operator, not an overloaded one.
1126 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1127 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1128}
1129
1130TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1131 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001132 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001133 EXPECT_TRUE(matches("class Y { }; "
1134 "bool operator&&(Y x, Y y) { return true; }; "
1135 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1136 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001137 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001138 EXPECT_TRUE(notMatches("class Y { }; "
1139 "bool operator&&(Y x, Y y) { return true; }; "
1140 "Y a; Y b; bool c = a && b;",
1141 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001142 StatementMatcher OpStarCall =
1143 operatorCallExpr(hasOverloadedOperatorName("*"));
1144 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1145 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001146 DeclarationMatcher ClassWithOpStar =
1147 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1148 EXPECT_TRUE(matches("class Y { int operator*(); };",
1149 ClassWithOpStar));
1150 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1151 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001152 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1153 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1154 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001155}
1156
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001157TEST(Matcher, NestedOverloadedOperatorCalls) {
1158 EXPECT_TRUE(matchAndVerifyResultTrue(
1159 "class Y { }; "
1160 "Y& operator&&(Y& x, Y& y) { return x; }; "
1161 "Y a; Y b; Y c; Y d = a && b && c;",
1162 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1163 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1164 EXPECT_TRUE(matches(
1165 "class Y { }; "
1166 "Y& operator&&(Y& x, Y& y) { return x; }; "
1167 "Y a; Y b; Y c; Y d = a && b && c;",
1168 operatorCallExpr(hasParent(operatorCallExpr()))));
1169 EXPECT_TRUE(matches(
1170 "class Y { }; "
1171 "Y& operator&&(Y& x, Y& y) { return x; }; "
1172 "Y a; Y b; Y c; Y d = a && b && c;",
1173 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1174}
1175
Manuel Klimek04616e42012-07-06 05:48:52 +00001176TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001177 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001178 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001179
1180 EXPECT_TRUE(
1181 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1182 MethodOnY));
1183 EXPECT_TRUE(
1184 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1185 MethodOnY));
1186 EXPECT_TRUE(
1187 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1188 MethodOnY));
1189 EXPECT_TRUE(
1190 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1191 MethodOnY));
1192 EXPECT_TRUE(
1193 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1194 MethodOnY));
1195
1196 EXPECT_TRUE(matches(
1197 "class Y {"
1198 " public: virtual void x();"
1199 "};"
1200 "class X : public Y {"
1201 " public: virtual void x();"
1202 "};"
1203 "void z() { X *x; x->Y::x(); }", MethodOnY));
1204}
1205
1206TEST(Matcher, VariableUsage) {
1207 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001208 declRefExpr(to(
1209 varDecl(hasInitializer(
1210 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001211
1212 EXPECT_TRUE(matches(
1213 "class Y {"
1214 " public:"
1215 " bool x() const;"
1216 "};"
1217 "void z(const Y &y) {"
1218 " bool b = y.x();"
1219 " if (b) {}"
1220 "}", Reference));
1221
1222 EXPECT_TRUE(notMatches(
1223 "class Y {"
1224 " public:"
1225 " bool x() const;"
1226 "};"
1227 "void z(const Y &y) {"
1228 " bool b = y.x();"
1229 "}", Reference));
1230}
1231
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001232TEST(Matcher, VarDecl_Storage) {
1233 auto M = varDecl(hasName("X"), hasLocalStorage());
1234 EXPECT_TRUE(matches("void f() { int X; }", M));
1235 EXPECT_TRUE(notMatches("int X;", M));
1236 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1237
1238 M = varDecl(hasName("X"), hasGlobalStorage());
1239 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1240 EXPECT_TRUE(matches("int X;", M));
1241 EXPECT_TRUE(matches("void f() { static int X; }", M));
1242}
1243
Manuel Klimek61379422012-12-04 14:42:08 +00001244TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001245 EXPECT_TRUE(matches(
1246 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001247 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001248}
1249
Manuel Klimek04616e42012-07-06 05:48:52 +00001250TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001251 StatementMatcher CallOnVariableY =
1252 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001253
1254 EXPECT_TRUE(matches(
1255 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1256 EXPECT_TRUE(matches(
1257 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1258 EXPECT_TRUE(matches(
1259 "class Y { public: void x(); };"
1260 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1261 EXPECT_TRUE(matches(
1262 "class Y { public: void x(); };"
1263 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1264 EXPECT_TRUE(notMatches(
1265 "class Y { public: void x(); };"
1266 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1267 CallOnVariableY));
1268}
1269
Daniel Jasper1dad1832012-07-10 20:20:19 +00001270TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1271 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1272 unaryExprOrTypeTraitExpr()));
1273 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1274 alignOfExpr(anything())));
1275 // FIXME: Uncomment once alignof is enabled.
1276 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1277 // unaryExprOrTypeTraitExpr()));
1278 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1279 // sizeOfExpr()));
1280}
1281
1282TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1283 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1284 hasArgumentOfType(asString("int")))));
1285 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1286 hasArgumentOfType(asString("float")))));
1287 EXPECT_TRUE(matches(
1288 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001289 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001290 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001291 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001292}
1293
Manuel Klimek04616e42012-07-06 05:48:52 +00001294TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001295 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001296}
1297
1298TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001299 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001300}
1301
1302TEST(MemberExpression, MatchesVariable) {
1303 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001304 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001305 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001306 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001307 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001308 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001309}
1310
1311TEST(MemberExpression, MatchesStaticVariable) {
1312 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001313 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001314 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001315 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001316 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001317 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001318}
1319
Daniel Jasper4e566c42012-07-12 08:50:38 +00001320TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001321 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1322 EXPECT_TRUE(matches(
1323 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1324 callExpr(hasArgument(0, declRefExpr(
1325 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001326}
1327
1328TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001329 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001330 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001331 callExpr(hasArgument(0, declRefExpr(
1332 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001333}
1334
Manuel Klimek04616e42012-07-06 05:48:52 +00001335TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1336 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001337 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001338 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001339 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001340 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001341 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001342}
1343
1344TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1345 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001346 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001347 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001348 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001349 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001350 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001351}
1352
1353TEST(IsArrow, MatchesMemberCallsViaArrow) {
1354 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001355 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001356 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001357 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001358 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001359 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001360}
1361
1362TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001363 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001364
1365 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1366 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1367}
1368
1369TEST(Callee, MatchesMemberExpressions) {
1370 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001371 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001372 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001373 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001374}
1375
1376TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001377 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001378
1379 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1380 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1381
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001382 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1383 llvm::Triple::Win32) {
1384 // FIXME: Make this work for MSVC.
1385 // Dependent contexts, but a non-dependent call.
1386 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1387 CallFunctionF));
1388 EXPECT_TRUE(
1389 matches("void f(); template <int N> struct S { void g() { f(); } };",
1390 CallFunctionF));
1391 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001392
1393 // Depedent calls don't match.
1394 EXPECT_TRUE(
1395 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1396 CallFunctionF));
1397 EXPECT_TRUE(
1398 notMatches("void f(int);"
1399 "template <typename T> struct S { void g(T t) { f(t); } };",
1400 CallFunctionF));
1401}
1402
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001403TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1404 EXPECT_TRUE(
1405 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001406 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001407}
1408
1409TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1410 EXPECT_TRUE(
1411 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001412 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001413}
1414
1415TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1416 EXPECT_TRUE(
1417 notMatches("void g(); template <typename T> void f(T t) {}"
1418 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001419 functionTemplateDecl(hasName("f"),
1420 hasDescendant(declRefExpr(to(
1421 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001422}
1423
Manuel Klimek04616e42012-07-06 05:48:52 +00001424TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001425 StatementMatcher CallArgumentY = callExpr(
1426 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001427
1428 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1429 EXPECT_TRUE(
1430 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1431 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1432
Daniel Jasper848cbe12012-09-18 13:09:13 +00001433 StatementMatcher WrongIndex = callExpr(
1434 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001435 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1436}
1437
1438TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001439 StatementMatcher CallArgumentY = callExpr(
1440 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001441 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1442 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1443 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1444}
1445
1446TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001447 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001448
1449 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1450 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1451 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1452}
1453
Daniel Jasper9f501292012-12-04 11:54:27 +00001454TEST(Matcher, ParameterCount) {
1455 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1456 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1457 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1458 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1459 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1460}
1461
Manuel Klimek04616e42012-07-06 05:48:52 +00001462TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001463 DeclarationMatcher ReferenceClassX = varDecl(
1464 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001465 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1466 ReferenceClassX));
1467 EXPECT_TRUE(
1468 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001469 // The match here is on the implicit copy constructor code for
1470 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001471 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001472 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1473 EXPECT_TRUE(
1474 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001475 EXPECT_TRUE(
1476 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1477}
1478
Edwin Vane0a4836e2013-03-06 17:02:57 +00001479TEST(QualType, hasCanonicalType) {
1480 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1481 "int a;"
1482 "int_ref b = a;",
1483 varDecl(hasType(qualType(referenceType())))));
1484 EXPECT_TRUE(
1485 matches("typedef int &int_ref;"
1486 "int a;"
1487 "int_ref b = a;",
1488 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1489}
1490
Edwin Vane119d3df2013-04-02 18:15:55 +00001491TEST(QualType, hasLocalQualifiers) {
1492 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1493 varDecl(hasType(hasLocalQualifiers()))));
1494 EXPECT_TRUE(matches("int *const j = nullptr;",
1495 varDecl(hasType(hasLocalQualifiers()))));
1496 EXPECT_TRUE(matches("int *volatile k;",
1497 varDecl(hasType(hasLocalQualifiers()))));
1498 EXPECT_TRUE(notMatches("int m;",
1499 varDecl(hasType(hasLocalQualifiers()))));
1500}
1501
Manuel Klimek04616e42012-07-06 05:48:52 +00001502TEST(HasParameter, CallsInnerMatcher) {
1503 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001504 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001505 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001506 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001507}
1508
1509TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1510 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001511 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001512}
1513
1514TEST(HasType, MatchesParameterVariableTypesStrictly) {
1515 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001516 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001517 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001518 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001519 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001520 methodDecl(hasParameter(0,
1521 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001522 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001523 methodDecl(hasParameter(0,
1524 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001525}
1526
1527TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1528 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001529 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001530 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001531 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001532}
1533
Daniel Jasper1dad1832012-07-10 20:20:19 +00001534TEST(Returns, MatchesReturnTypes) {
1535 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001536 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001537 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001538 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001539 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001540 functionDecl(returns(hasDeclaration(
1541 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001542}
1543
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001544TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001545 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1546 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1547 functionDecl(isExternC())));
1548 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001549}
1550
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001551TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1552 EXPECT_TRUE(
1553 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1554 EXPECT_TRUE(matches("void Func() = delete;",
1555 functionDecl(hasName("Func"), isDeleted())));
1556}
1557
Manuel Klimek04616e42012-07-06 05:48:52 +00001558TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1559 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001560 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001561}
1562
1563TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1564 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001565 methodDecl(hasAnyParameter(hasType(pointsTo(
1566 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001567}
1568
Alp Toker8db6e7a2014-01-05 06:38:57 +00001569TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001570 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001571 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001572 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001573 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001574}
1575
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001576TEST(Matcher, MatchesClassTemplateSpecialization) {
1577 EXPECT_TRUE(matches("template<typename T> struct A {};"
1578 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001579 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001580 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001581 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001582 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001583 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001584}
1585
Manuel Klimekc16c6522013-06-20 13:08:29 +00001586TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1587 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1588 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1589}
1590
1591TEST(ParmVarDecl, MatchesParmVars) {
1592 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1593 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1594}
1595
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001596TEST(Matcher, MatchesTypeTemplateArgument) {
1597 EXPECT_TRUE(matches(
1598 "template<typename T> struct B {};"
1599 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001600 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001601 asString("int"))))));
1602}
1603
1604TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1605 EXPECT_TRUE(matches(
1606 "struct B { int next; };"
1607 "template<int(B::*next_ptr)> struct A {};"
1608 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001609 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1610 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001611
1612 EXPECT_TRUE(notMatches(
1613 "template <typename T> struct A {};"
1614 "A<int> a;",
1615 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1616 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001617
1618 EXPECT_TRUE(matches(
1619 "struct B { int next; };"
1620 "template<int(B::*next_ptr)> struct A {};"
1621 "A<&B::next> a;",
1622 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1623 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1624
1625 EXPECT_TRUE(notMatches(
1626 "template <typename T> struct A {};"
1627 "A<int> a;",
1628 templateSpecializationType(hasAnyTemplateArgument(
1629 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001630}
1631
1632TEST(Matcher, MatchesSpecificArgument) {
1633 EXPECT_TRUE(matches(
1634 "template<typename T, typename U> class A {};"
1635 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001636 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001637 1, refersToType(asString("int"))))));
1638 EXPECT_TRUE(notMatches(
1639 "template<typename T, typename U> class A {};"
1640 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001641 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001642 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001643
1644 EXPECT_TRUE(matches(
1645 "template<typename T, typename U> class A {};"
1646 "A<bool, int> a;",
1647 templateSpecializationType(hasTemplateArgument(
1648 1, refersToType(asString("int"))))));
1649 EXPECT_TRUE(notMatches(
1650 "template<typename T, typename U> class A {};"
1651 "A<int, bool> a;",
1652 templateSpecializationType(hasTemplateArgument(
1653 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001654}
1655
Daniel Jasper639522c2013-02-25 12:02:08 +00001656TEST(Matcher, MatchesAccessSpecDecls) {
1657 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1658 EXPECT_TRUE(
1659 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1660 EXPECT_TRUE(
1661 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1662 EXPECT_TRUE(
1663 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1664
1665 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1666}
1667
Edwin Vane37ee1d72013-04-09 20:46:36 +00001668TEST(Matcher, MatchesVirtualMethod) {
1669 EXPECT_TRUE(matches("class X { virtual int f(); };",
1670 methodDecl(isVirtual(), hasName("::X::f"))));
1671 EXPECT_TRUE(notMatches("class X { int f(); };",
1672 methodDecl(isVirtual())));
1673}
1674
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001675TEST(Matcher, MatchesPureMethod) {
1676 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1677 methodDecl(isPure(), hasName("::X::f"))));
1678 EXPECT_TRUE(notMatches("class X { int f(); };",
1679 methodDecl(isPure())));
1680}
1681
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001682TEST(Matcher, MatchesConstMethod) {
1683 EXPECT_TRUE(matches("struct A { void foo() const; };",
1684 methodDecl(isConst())));
1685 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1686 methodDecl(isConst())));
1687}
1688
Edwin Vane37ee1d72013-04-09 20:46:36 +00001689TEST(Matcher, MatchesOverridingMethod) {
1690 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1691 "class Y : public X { int f(); };",
1692 methodDecl(isOverride(), hasName("::Y::f"))));
1693 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1694 "class Y : public X { int f(); };",
1695 methodDecl(isOverride(), hasName("::X::f"))));
1696 EXPECT_TRUE(notMatches("class X { int f(); }; "
1697 "class Y : public X { int f(); };",
1698 methodDecl(isOverride())));
1699 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1700 methodDecl(isOverride())));
1701}
1702
Manuel Klimek04616e42012-07-06 05:48:52 +00001703TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001704 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001705
1706 EXPECT_TRUE(
1707 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1708 EXPECT_TRUE(
1709 matches("class X { public: X(); }; void x() { X x = X(); }",
1710 Constructor));
1711 EXPECT_TRUE(
1712 matches("class X { public: X(int); }; void x() { X x = 0; }",
1713 Constructor));
1714 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1715}
1716
1717TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001718 StatementMatcher Constructor = constructExpr(
1719 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001720
1721 EXPECT_TRUE(
1722 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1723 Constructor));
1724 EXPECT_TRUE(
1725 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1726 Constructor));
1727 EXPECT_TRUE(
1728 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1729 Constructor));
1730 EXPECT_TRUE(
1731 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1732 Constructor));
1733
Daniel Jasper848cbe12012-09-18 13:09:13 +00001734 StatementMatcher WrongIndex = constructExpr(
1735 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001736 EXPECT_TRUE(
1737 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1738 WrongIndex));
1739}
1740
1741TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001742 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001743
1744 EXPECT_TRUE(
1745 matches("class X { public: X(int); }; void x() { X x(0); }",
1746 Constructor1Arg));
1747 EXPECT_TRUE(
1748 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1749 Constructor1Arg));
1750 EXPECT_TRUE(
1751 matches("class X { public: X(int); }; void x() { X x = 0; }",
1752 Constructor1Arg));
1753 EXPECT_TRUE(
1754 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1755 Constructor1Arg));
1756}
1757
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001758TEST(Matcher, ConstructorListInitialization) {
1759 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1760
1761 EXPECT_TRUE(
1762 matches("class X { public: X(int); }; void x() { X x{0}; }",
1763 ConstructorListInit));
1764 EXPECT_FALSE(
1765 matches("class X { public: X(int); }; void x() { X x(0); }",
1766 ConstructorListInit));
1767}
1768
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001769TEST(Matcher,ThisExpr) {
1770 EXPECT_TRUE(
1771 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1772 EXPECT_TRUE(
1773 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1774}
1775
Manuel Klimek04616e42012-07-06 05:48:52 +00001776TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001777 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001778
1779 std::string ClassString = "class string { public: string(); ~string(); }; ";
1780
1781 EXPECT_TRUE(
1782 matches(ClassString +
1783 "string GetStringByValue();"
1784 "void FunctionTakesString(string s);"
1785 "void run() { FunctionTakesString(GetStringByValue()); }",
1786 TempExpression));
1787
1788 EXPECT_TRUE(
1789 notMatches(ClassString +
1790 "string* GetStringPointer(); "
1791 "void FunctionTakesStringPtr(string* s);"
1792 "void run() {"
1793 " string* s = GetStringPointer();"
1794 " FunctionTakesStringPtr(GetStringPointer());"
1795 " FunctionTakesStringPtr(s);"
1796 "}",
1797 TempExpression));
1798
1799 EXPECT_TRUE(
1800 notMatches("class no_dtor {};"
1801 "no_dtor GetObjByValue();"
1802 "void ConsumeObj(no_dtor param);"
1803 "void run() { ConsumeObj(GetObjByValue()); }",
1804 TempExpression));
1805}
1806
Sam Panzer68a35af2012-08-24 22:04:44 +00001807TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1808 std::string ClassString =
1809 "class string { public: string(); int length(); }; ";
1810
1811 EXPECT_TRUE(
1812 matches(ClassString +
1813 "string GetStringByValue();"
1814 "void FunctionTakesString(string s);"
1815 "void run() { FunctionTakesString(GetStringByValue()); }",
1816 materializeTemporaryExpr()));
1817
1818 EXPECT_TRUE(
1819 notMatches(ClassString +
1820 "string* GetStringPointer(); "
1821 "void FunctionTakesStringPtr(string* s);"
1822 "void run() {"
1823 " string* s = GetStringPointer();"
1824 " FunctionTakesStringPtr(GetStringPointer());"
1825 " FunctionTakesStringPtr(s);"
1826 "}",
1827 materializeTemporaryExpr()));
1828
1829 EXPECT_TRUE(
1830 notMatches(ClassString +
1831 "string GetStringByValue();"
1832 "void run() { int k = GetStringByValue().length(); }",
1833 materializeTemporaryExpr()));
1834
1835 EXPECT_TRUE(
1836 notMatches(ClassString +
1837 "string GetStringByValue();"
1838 "void run() { GetStringByValue(); }",
1839 materializeTemporaryExpr()));
1840}
1841
Manuel Klimek04616e42012-07-06 05:48:52 +00001842TEST(ConstructorDeclaration, SimpleCase) {
1843 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001844 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001845 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001846 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001847}
1848
1849TEST(ConstructorDeclaration, IsImplicit) {
1850 // This one doesn't match because the constructor is not added by the
1851 // compiler (it is not needed).
1852 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001853 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001854 // The compiler added the implicit default constructor.
1855 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001856 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001857 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001858 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001859 // The compiler added an implicit assignment operator.
1860 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1861 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001862}
1863
Daniel Jasper1dad1832012-07-10 20:20:19 +00001864TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1865 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001866 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001867}
1868
1869TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001870 EXPECT_TRUE(notMatches("class Foo {};",
1871 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001872}
1873
Manuel Klimek04616e42012-07-06 05:48:52 +00001874TEST(HasAnyConstructorInitializer, SimpleCase) {
1875 EXPECT_TRUE(notMatches(
1876 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001877 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001878 EXPECT_TRUE(matches(
1879 "class Foo {"
1880 " Foo() : foo_() { }"
1881 " int foo_;"
1882 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001883 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001884}
1885
1886TEST(HasAnyConstructorInitializer, ForField) {
1887 static const char Code[] =
1888 "class Baz { };"
1889 "class Foo {"
1890 " Foo() : foo_() { }"
1891 " Baz foo_;"
1892 " Baz bar_;"
1893 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001894 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1895 forField(hasType(recordDecl(hasName("Baz"))))))));
1896 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001897 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001898 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1899 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001900}
1901
1902TEST(HasAnyConstructorInitializer, WithInitializer) {
1903 static const char Code[] =
1904 "class Foo {"
1905 " Foo() : foo_(0) { }"
1906 " int foo_;"
1907 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001908 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001909 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001910 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001911 withInitializer(integerLiteral(equals(1)))))));
1912}
1913
1914TEST(HasAnyConstructorInitializer, IsWritten) {
1915 static const char Code[] =
1916 "struct Bar { Bar(){} };"
1917 "class Foo {"
1918 " Foo() : foo_() { }"
1919 " Bar foo_;"
1920 " Bar bar_;"
1921 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001922 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001923 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001924 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001925 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001926 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001927 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1928}
1929
1930TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001931 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001932
1933 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
1934 EXPECT_TRUE(
1935 matches("class X { public: X(); }; void x() { new X(); }", New));
1936 EXPECT_TRUE(
1937 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1938 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
1939}
1940
1941TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001942 StatementMatcher New = constructExpr(
1943 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001944
1945 EXPECT_TRUE(
1946 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1947 New));
1948 EXPECT_TRUE(
1949 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1950 New));
1951 EXPECT_TRUE(
1952 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
1953 New));
1954
Daniel Jasper848cbe12012-09-18 13:09:13 +00001955 StatementMatcher WrongIndex = constructExpr(
1956 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001957 EXPECT_TRUE(
1958 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
1959 WrongIndex));
1960}
1961
1962TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001963 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001964
1965 EXPECT_TRUE(
1966 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1967 EXPECT_TRUE(
1968 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
1969 New));
1970}
1971
Daniel Jasper1dad1832012-07-10 20:20:19 +00001972TEST(Matcher, DeleteExpression) {
1973 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001974 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001975}
1976
Manuel Klimek04616e42012-07-06 05:48:52 +00001977TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001978 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001979
1980 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
1981 EXPECT_TRUE(
1982 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
1983 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
1984}
1985
1986TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001987 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001988 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
1989 // wide string
1990 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
1991 // with escaped characters
1992 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
1993 // no matching -- though the data type is the same, there is no string literal
1994 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
1995}
1996
1997TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001998 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001999 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2000 // wide character
2001 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2002 // wide character, Hex encoded, NOT MATCHED!
2003 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2004 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2005}
2006
2007TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002008 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002009 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2010 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2011 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2012 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2013
2014 // Non-matching cases (character literals, float and double)
2015 EXPECT_TRUE(notMatches("int i = L'a';",
2016 HasIntLiteral)); // this is actually a character
2017 // literal cast to int
2018 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2019 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2020 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2021}
2022
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002023TEST(Matcher, FloatLiterals) {
2024 StatementMatcher HasFloatLiteral = floatLiteral();
2025 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2026 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2027 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2028 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2029 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
2030
2031 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
2032}
2033
Daniel Jasper5901e472012-10-01 13:40:41 +00002034TEST(Matcher, NullPtrLiteral) {
2035 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2036}
2037
Daniel Jasper87c3d362012-09-20 14:12:57 +00002038TEST(Matcher, AsmStatement) {
2039 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2040}
2041
Manuel Klimek04616e42012-07-06 05:48:52 +00002042TEST(Matcher, Conditions) {
2043 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2044
2045 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2046 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2047 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2048 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2049 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2050}
2051
Manuel Klimek909b5c942014-05-27 10:04:12 +00002052TEST(IfStmt, ChildTraversalMatchers) {
2053 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2054 ifStmt(hasThen(boolLiteral(equals(true))))));
2055 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2056 ifStmt(hasThen(boolLiteral(equals(true))))));
2057 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2058 ifStmt(hasElse(boolLiteral(equals(true))))));
2059 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2060 ifStmt(hasElse(boolLiteral(equals(true))))));
2061}
2062
Manuel Klimek04616e42012-07-06 05:48:52 +00002063TEST(MatchBinaryOperator, HasOperatorName) {
2064 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2065
2066 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2067 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2068}
2069
2070TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2071 StatementMatcher OperatorTrueFalse =
2072 binaryOperator(hasLHS(boolLiteral(equals(true))),
2073 hasRHS(boolLiteral(equals(false))));
2074
2075 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2076 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2077 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2078}
2079
2080TEST(MatchBinaryOperator, HasEitherOperand) {
2081 StatementMatcher HasOperand =
2082 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2083
2084 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2085 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2086 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2087}
2088
2089TEST(Matcher, BinaryOperatorTypes) {
2090 // Integration test that verifies the AST provides all binary operators in
2091 // a way we expect.
2092 // FIXME: Operator ','
2093 EXPECT_TRUE(
2094 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2095 EXPECT_TRUE(
2096 matches("bool b; bool c = (b = true);",
2097 binaryOperator(hasOperatorName("="))));
2098 EXPECT_TRUE(
2099 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2100 EXPECT_TRUE(
2101 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2102 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2103 EXPECT_TRUE(
2104 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2105 EXPECT_TRUE(
2106 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2107 EXPECT_TRUE(
2108 matches("int i = 1; int j = (i <<= 2);",
2109 binaryOperator(hasOperatorName("<<="))));
2110 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2111 EXPECT_TRUE(
2112 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2113 EXPECT_TRUE(
2114 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2115 EXPECT_TRUE(
2116 matches("int i = 1; int j = (i >>= 2);",
2117 binaryOperator(hasOperatorName(">>="))));
2118 EXPECT_TRUE(
2119 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2120 EXPECT_TRUE(
2121 matches("int i = 42; int j = (i ^= 42);",
2122 binaryOperator(hasOperatorName("^="))));
2123 EXPECT_TRUE(
2124 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2125 EXPECT_TRUE(
2126 matches("int i = 42; int j = (i %= 42);",
2127 binaryOperator(hasOperatorName("%="))));
2128 EXPECT_TRUE(
2129 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2130 EXPECT_TRUE(
2131 matches("bool b = true && false;",
2132 binaryOperator(hasOperatorName("&&"))));
2133 EXPECT_TRUE(
2134 matches("bool b = true; bool c = (b &= false);",
2135 binaryOperator(hasOperatorName("&="))));
2136 EXPECT_TRUE(
2137 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2138 EXPECT_TRUE(
2139 matches("bool b = true || false;",
2140 binaryOperator(hasOperatorName("||"))));
2141 EXPECT_TRUE(
2142 matches("bool b = true; bool c = (b |= false);",
2143 binaryOperator(hasOperatorName("|="))));
2144 EXPECT_TRUE(
2145 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2146 EXPECT_TRUE(
2147 matches("int i = 42; int j = (i *= 23);",
2148 binaryOperator(hasOperatorName("*="))));
2149 EXPECT_TRUE(
2150 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2151 EXPECT_TRUE(
2152 matches("int i = 42; int j = (i /= 23);",
2153 binaryOperator(hasOperatorName("/="))));
2154 EXPECT_TRUE(
2155 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2156 EXPECT_TRUE(
2157 matches("int i = 42; int j = (i += 23);",
2158 binaryOperator(hasOperatorName("+="))));
2159 EXPECT_TRUE(
2160 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2161 EXPECT_TRUE(
2162 matches("int i = 42; int j = (i -= 23);",
2163 binaryOperator(hasOperatorName("-="))));
2164 EXPECT_TRUE(
2165 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2166 binaryOperator(hasOperatorName("->*"))));
2167 EXPECT_TRUE(
2168 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2169 binaryOperator(hasOperatorName(".*"))));
2170
2171 // Member expressions as operators are not supported in matches.
2172 EXPECT_TRUE(
2173 notMatches("struct A { void x(A *a) { a->x(this); } };",
2174 binaryOperator(hasOperatorName("->"))));
2175
2176 // Initializer assignments are not represented as operator equals.
2177 EXPECT_TRUE(
2178 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2179
2180 // Array indexing is not represented as operator.
2181 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2182
2183 // Overloaded operators do not match at all.
2184 EXPECT_TRUE(notMatches(
2185 "struct A { bool operator&&(const A &a) const { return false; } };"
2186 "void x() { A a, b; a && b; }",
2187 binaryOperator()));
2188}
2189
2190TEST(MatchUnaryOperator, HasOperatorName) {
2191 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2192
2193 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2194 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2195}
2196
2197TEST(MatchUnaryOperator, HasUnaryOperand) {
2198 StatementMatcher OperatorOnFalse =
2199 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2200
2201 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2202 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2203}
2204
2205TEST(Matcher, UnaryOperatorTypes) {
2206 // Integration test that verifies the AST provides all unary operators in
2207 // a way we expect.
2208 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2209 EXPECT_TRUE(
2210 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2211 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2212 EXPECT_TRUE(
2213 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2214 EXPECT_TRUE(
2215 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2216 EXPECT_TRUE(
2217 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2218 EXPECT_TRUE(
2219 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2220 EXPECT_TRUE(
2221 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2222 EXPECT_TRUE(
2223 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2224 EXPECT_TRUE(
2225 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2226
2227 // We don't match conversion operators.
2228 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2229
2230 // Function calls are not represented as operator.
2231 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2232
2233 // Overloaded operators do not match at all.
2234 // FIXME: We probably want to add that.
2235 EXPECT_TRUE(notMatches(
2236 "struct A { bool operator!() const { return false; } };"
2237 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2238}
2239
2240TEST(Matcher, ConditionalOperator) {
2241 StatementMatcher Conditional = conditionalOperator(
2242 hasCondition(boolLiteral(equals(true))),
2243 hasTrueExpression(boolLiteral(equals(false))));
2244
2245 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2246 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2247 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2248
2249 StatementMatcher ConditionalFalse = conditionalOperator(
2250 hasFalseExpression(boolLiteral(equals(false))));
2251
2252 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2253 EXPECT_TRUE(
2254 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2255}
2256
Daniel Jasper1dad1832012-07-10 20:20:19 +00002257TEST(ArraySubscriptMatchers, ArraySubscripts) {
2258 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2259 arraySubscriptExpr()));
2260 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2261 arraySubscriptExpr()));
2262}
2263
2264TEST(ArraySubscriptMatchers, ArrayIndex) {
2265 EXPECT_TRUE(matches(
2266 "int i[2]; void f() { i[1] = 1; }",
2267 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2268 EXPECT_TRUE(matches(
2269 "int i[2]; void f() { 1[i] = 1; }",
2270 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2271 EXPECT_TRUE(notMatches(
2272 "int i[2]; void f() { i[1] = 1; }",
2273 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2274}
2275
2276TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2277 EXPECT_TRUE(matches(
2278 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002279 arraySubscriptExpr(hasBase(implicitCastExpr(
2280 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002281}
2282
Manuel Klimek04616e42012-07-06 05:48:52 +00002283TEST(Matcher, HasNameSupportsNamespaces) {
2284 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002285 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002286 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002287 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002288 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002289 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002290 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002291 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002292 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002293 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002294 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002295 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002296 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002297 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002298 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002299 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002300 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002301 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002302 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002303 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002304 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002305 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002306 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002307 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002308}
2309
2310TEST(Matcher, HasNameSupportsOuterClasses) {
2311 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002312 matches("class A { class B { class C; }; };",
2313 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002314 EXPECT_TRUE(
2315 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002316 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002317 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002318 matches("class A { class B { class C; }; };",
2319 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002320 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002321 matches("class A { class B { class C; }; };",
2322 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002323 EXPECT_TRUE(
2324 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002325 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002326 EXPECT_TRUE(
2327 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002328 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002329 EXPECT_TRUE(
2330 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002331 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002332 EXPECT_TRUE(
2333 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002334 recordDecl(hasName("::C"))));
2335 EXPECT_TRUE(
2336 notMatches("class A { class B { class C; }; };",
2337 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002338 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002339 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002340 EXPECT_TRUE(
2341 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002342 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002343}
2344
2345TEST(Matcher, IsDefinition) {
2346 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002347 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002348 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2349 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2350
2351 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002352 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002353 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2354 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2355
2356 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002357 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002358 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2359 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2360}
2361
2362TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002363 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002364 ofClass(hasName("X")))));
2365
2366 EXPECT_TRUE(
2367 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2368 EXPECT_TRUE(
2369 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2370 Constructor));
2371 EXPECT_TRUE(
2372 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2373 Constructor));
2374}
2375
2376TEST(Matcher, VisitsTemplateInstantiations) {
2377 EXPECT_TRUE(matches(
2378 "class A { public: void x(); };"
2379 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002380 "void f() { B<A> b; b.y(); }",
2381 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002382
2383 EXPECT_TRUE(matches(
2384 "class A { public: void x(); };"
2385 "class C {"
2386 " public:"
2387 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2388 "};"
2389 "void f() {"
2390 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002391 "}",
2392 recordDecl(hasName("C"),
2393 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002394}
2395
Daniel Jasper1dad1832012-07-10 20:20:19 +00002396TEST(Matcher, HandlesNullQualTypes) {
2397 // FIXME: Add a Type matcher so we can replace uses of this
2398 // variable with Type(True())
2399 const TypeMatcher AnyType = anything();
2400
2401 // We don't really care whether this matcher succeeds; we're testing that
2402 // it completes without crashing.
2403 EXPECT_TRUE(matches(
2404 "struct A { };"
2405 "template <typename T>"
2406 "void f(T t) {"
2407 " T local_t(t /* this becomes a null QualType in the AST */);"
2408 "}"
2409 "void g() {"
2410 " f(0);"
2411 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002412 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002413 anyOf(
2414 TypeMatcher(hasDeclaration(anything())),
2415 pointsTo(AnyType),
2416 references(AnyType)
2417 // Other QualType matchers should go here.
2418 ))))));
2419}
2420
Manuel Klimek04616e42012-07-06 05:48:52 +00002421// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002422AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002423 // Make sure all special variables are used: node, match_finder,
2424 // bound_nodes_builder, and the parameter named 'AMatcher'.
2425 return AMatcher.matches(Node, Finder, Builder);
2426}
2427
2428TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002429 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002430
2431 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002432 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002433
2434 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002435 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002436
2437 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002438 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002439}
2440
2441AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +00002442 polymorphicHas,
2443 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2444 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002445 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002446 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002447 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2448 ASTMatchFinder::BK_First);
2449}
2450
2451TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002452 DeclarationMatcher HasClassB =
2453 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002454
2455 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002456 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002457
2458 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002459 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002460
2461 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002462 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002463
2464 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002465 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002466
2467 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2468}
2469
2470TEST(For, FindsForLoops) {
2471 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2472 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002473 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2474 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002475 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002476}
2477
Daniel Jasper4e566c42012-07-12 08:50:38 +00002478TEST(For, ForLoopInternals) {
2479 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2480 forStmt(hasCondition(anything()))));
2481 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2482 forStmt(hasLoopInit(anything()))));
2483}
2484
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002485TEST(For, ForRangeLoopInternals) {
2486 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2487 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002488 EXPECT_TRUE(matches(
2489 "void f(){ int a[] {1, 2}; for (int i : a); }",
2490 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002491}
2492
Daniel Jasper4e566c42012-07-12 08:50:38 +00002493TEST(For, NegativeForLoopInternals) {
2494 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002495 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002496 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2497 forStmt(hasLoopInit(anything()))));
2498}
2499
Manuel Klimek04616e42012-07-06 05:48:52 +00002500TEST(For, ReportsNoFalsePositives) {
2501 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2502 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2503}
2504
2505TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002506 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2507 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2508 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002509}
2510
2511TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2512 // It's not a compound statement just because there's "{}" in the source
2513 // text. This is an AST search, not grep.
2514 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002515 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002516 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002517 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002518}
2519
Daniel Jasper4e566c42012-07-12 08:50:38 +00002520TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002521 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002522 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002523 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002524 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002525 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002526 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002527 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002528 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002529 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2530 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002531}
2532
2533TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2534 // The simplest case: every compound statement is in a function
2535 // definition, and the function body itself must be a compound
2536 // statement.
2537 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002538 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002539}
2540
2541TEST(HasAnySubstatement, IsNotRecursive) {
2542 // It's really "has any immediate substatement".
2543 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002544 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002545}
2546
2547TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2548 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002549 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002550}
2551
2552TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2553 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002554 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002555}
2556
2557TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2558 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002559 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002560 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002561 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002562}
2563
2564TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2565 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002566 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002567 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002568 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002569 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002570 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002571}
2572
2573TEST(StatementCountIs, WorksWithMultipleStatements) {
2574 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002575 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002576}
2577
2578TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2579 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002580 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002581 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002582 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002583 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002584 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002585 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002586 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002587}
2588
2589TEST(Member, WorksInSimplestCase) {
2590 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002591 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002592}
2593
2594TEST(Member, DoesNotMatchTheBaseExpression) {
2595 // Don't pick out the wrong part of the member expression, this should
2596 // be checking the member (name) only.
2597 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002598 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002599}
2600
2601TEST(Member, MatchesInMemberFunctionCall) {
2602 EXPECT_TRUE(matches("void f() {"
2603 " struct { void first() {}; } s;"
2604 " s.first();"
2605 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002606 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002607}
2608
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002609TEST(Member, MatchesMember) {
2610 EXPECT_TRUE(matches(
2611 "struct A { int i; }; void f() { A a; a.i = 2; }",
2612 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2613 EXPECT_TRUE(notMatches(
2614 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2615 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2616}
2617
Daniel Jasper639522c2013-02-25 12:02:08 +00002618TEST(Member, UnderstandsAccess) {
2619 EXPECT_TRUE(matches(
2620 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2621 EXPECT_TRUE(notMatches(
2622 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2623 EXPECT_TRUE(notMatches(
2624 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2625
2626 EXPECT_TRUE(notMatches(
2627 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2628 EXPECT_TRUE(notMatches(
2629 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2630 EXPECT_TRUE(matches(
2631 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2632
2633 EXPECT_TRUE(notMatches(
2634 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2635 EXPECT_TRUE(matches("class A { protected: int i; };",
2636 fieldDecl(isProtected(), hasName("i"))));
2637 EXPECT_TRUE(notMatches(
2638 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2639
2640 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2641 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2642 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2643 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2644}
2645
Dmitri Gribenko06963042012-08-18 00:29:27 +00002646TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002647 // Fails in C++11 mode
2648 EXPECT_TRUE(matchesConditionally(
2649 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2650 "class X { void *operator new(std::size_t); };",
2651 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002652
2653 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002654 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002655
Daniel Jasper5901e472012-10-01 13:40:41 +00002656 // Fails in C++11 mode
2657 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002658 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2659 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002660 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002661}
2662
Manuel Klimek04616e42012-07-06 05:48:52 +00002663TEST(HasObjectExpression, DoesNotMatchMember) {
2664 EXPECT_TRUE(notMatches(
2665 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002666 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002667}
2668
2669TEST(HasObjectExpression, MatchesBaseOfVariable) {
2670 EXPECT_TRUE(matches(
2671 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002672 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002673 EXPECT_TRUE(matches(
2674 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002675 memberExpr(hasObjectExpression(
2676 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002677}
2678
2679TEST(HasObjectExpression,
2680 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2681 EXPECT_TRUE(matches(
2682 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002683 memberExpr(hasObjectExpression(
2684 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002685 EXPECT_TRUE(matches(
2686 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002687 memberExpr(hasObjectExpression(
2688 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002689}
2690
2691TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002692 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2693 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2694 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2695 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002696}
2697
2698TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002699 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002700}
2701
2702TEST(IsConstQualified, MatchesConstInt) {
2703 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002704 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002705}
2706
2707TEST(IsConstQualified, MatchesConstPointer) {
2708 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002709 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002710}
2711
2712TEST(IsConstQualified, MatchesThroughTypedef) {
2713 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002714 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002715 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002716 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002717}
2718
2719TEST(IsConstQualified, DoesNotMatchInappropriately) {
2720 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002721 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002722 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002723 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002724}
2725
Sam Panzer80c13772012-08-16 16:58:10 +00002726TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002727 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2728 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2729 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2730 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002731}
2732TEST(CastExpression, MatchesImplicitCasts) {
2733 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002734 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002735 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002736 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002737}
2738
2739TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002740 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2741 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2742 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2743 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002744}
2745
Manuel Klimek04616e42012-07-06 05:48:52 +00002746TEST(ReinterpretCast, MatchesSimpleCase) {
2747 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002748 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002749}
2750
2751TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002752 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002753 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002754 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002755 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002756 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002757 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2758 "B b;"
2759 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002760 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002761}
2762
2763TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002764 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002765 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002766 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002767}
2768
2769TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002770 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002771 EXPECT_TRUE(
2772 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002773 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002774 EXPECT_TRUE(
2775 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002776 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002777}
2778
2779TEST(DynamicCast, MatchesSimpleCase) {
2780 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2781 "B b;"
2782 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002783 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002784}
2785
2786TEST(StaticCast, MatchesSimpleCase) {
2787 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002788 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002789}
2790
2791TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002792 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002793 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002794 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002795 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002796 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002797 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2798 "B b;"
2799 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002800 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002801}
2802
Daniel Jasper417f7762012-09-18 13:36:17 +00002803TEST(CStyleCast, MatchesSimpleCase) {
2804 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2805}
2806
2807TEST(CStyleCast, DoesNotMatchOtherCasts) {
2808 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2809 "char q, *r = const_cast<char*>(&q);"
2810 "void* s = reinterpret_cast<char*>(&s);"
2811 "struct B { virtual ~B() {} }; struct D : B {};"
2812 "B b;"
2813 "D* t = dynamic_cast<D*>(&b);",
2814 cStyleCastExpr()));
2815}
2816
Manuel Klimek04616e42012-07-06 05:48:52 +00002817TEST(HasDestinationType, MatchesSimpleCase) {
2818 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002819 staticCastExpr(hasDestinationType(
2820 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002821}
2822
Sam Panzer80c13772012-08-16 16:58:10 +00002823TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2824 // This test creates an implicit const cast.
2825 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002826 implicitCastExpr(
2827 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002828 // This test creates an implicit array-to-pointer cast.
2829 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002830 implicitCastExpr(hasImplicitDestinationType(
2831 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002832}
2833
2834TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2835 // This test creates an implicit cast from int to char.
2836 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002837 implicitCastExpr(hasImplicitDestinationType(
2838 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002839 // This test creates an implicit array-to-pointer cast.
2840 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002841 implicitCastExpr(hasImplicitDestinationType(
2842 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002843}
2844
2845TEST(ImplicitCast, MatchesSimpleCase) {
2846 // This test creates an implicit const cast.
2847 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002848 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002849 // This test creates an implicit cast from int to char.
2850 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002851 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002852 // This test creates an implicit array-to-pointer cast.
2853 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002854 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002855}
2856
2857TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002858 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002859 // are present, and that it ignores explicit and paren casts.
2860
2861 // These two test cases have no casts.
2862 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002863 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002864 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002865 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002866
2867 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002868 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002869 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002870 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002871
2872 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002873 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002874}
2875
2876TEST(IgnoringImpCasts, MatchesImpCasts) {
2877 // This test checks that ignoringImpCasts matches when implicit casts are
2878 // present and its inner matcher alone does not match.
2879 // Note that this test creates an implicit const cast.
2880 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002881 varDecl(hasInitializer(ignoringImpCasts(
2882 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002883 // This test creates an implict cast from int to char.
2884 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002885 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002886 integerLiteral(equals(0)))))));
2887}
2888
2889TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2890 // These tests verify that ignoringImpCasts does not match if the inner
2891 // matcher does not match.
2892 // Note that the first test creates an implicit const cast.
2893 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002894 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002895 unless(anything()))))));
2896 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002897 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002898 unless(anything()))))));
2899
2900 // These tests verify that ignoringImplictCasts does not look through explicit
2901 // casts or parentheses.
2902 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002903 varDecl(hasInitializer(ignoringImpCasts(
2904 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002905 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002906 varDecl(hasInitializer(ignoringImpCasts(
2907 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002908 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002909 varDecl(hasInitializer(ignoringImpCasts(
2910 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002911 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002912 varDecl(hasInitializer(ignoringImpCasts(
2913 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002914}
2915
2916TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2917 // This test verifies that expressions that do not have implicit casts
2918 // still match the inner matcher.
2919 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002920 varDecl(hasInitializer(ignoringImpCasts(
2921 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002922}
2923
2924TEST(IgnoringParenCasts, MatchesParenCasts) {
2925 // This test checks that ignoringParenCasts matches when parentheses and/or
2926 // casts are present and its inner matcher alone does not match.
2927 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002928 varDecl(hasInitializer(ignoringParenCasts(
2929 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002930 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002931 varDecl(hasInitializer(ignoringParenCasts(
2932 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002933
2934 // This test creates an implict cast from int to char in addition to the
2935 // parentheses.
2936 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002937 varDecl(hasInitializer(ignoringParenCasts(
2938 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002939
2940 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002941 varDecl(hasInitializer(ignoringParenCasts(
2942 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002943 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002944 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002945 integerLiteral(equals(0)))))));
2946}
2947
2948TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
2949 // This test verifies that expressions that do not have any casts still match.
2950 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002951 varDecl(hasInitializer(ignoringParenCasts(
2952 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002953}
2954
2955TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
2956 // These tests verify that ignoringImpCasts does not match if the inner
2957 // matcher does not match.
2958 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002959 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002960 unless(anything()))))));
2961
2962 // This test creates an implicit cast from int to char in addition to the
2963 // parentheses.
2964 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002965 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002966 unless(anything()))))));
2967
2968 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002969 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002970 unless(anything()))))));
2971}
2972
2973TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
2974 // This test checks that ignoringParenAndImpCasts matches when
2975 // parentheses and/or implicit casts are present and its inner matcher alone
2976 // does not match.
2977 // Note that this test creates an implicit const cast.
2978 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002979 varDecl(hasInitializer(ignoringParenImpCasts(
2980 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002981 // This test creates an implicit cast from int to char.
2982 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002983 varDecl(hasInitializer(ignoringParenImpCasts(
2984 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002985}
2986
2987TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
2988 // This test verifies that expressions that do not have parentheses or
2989 // implicit casts still match.
2990 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002991 varDecl(hasInitializer(ignoringParenImpCasts(
2992 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002993 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002994 varDecl(hasInitializer(ignoringParenImpCasts(
2995 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002996}
2997
2998TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
2999 // These tests verify that ignoringParenImpCasts does not match if
3000 // the inner matcher does not match.
3001 // This test creates an implicit cast.
3002 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003003 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003004 unless(anything()))))));
3005 // These tests verify that ignoringParenAndImplictCasts does not look
3006 // through explicit casts.
3007 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003008 varDecl(hasInitializer(ignoringParenImpCasts(
3009 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003010 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003011 varDecl(hasInitializer(ignoringParenImpCasts(
3012 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003013 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003014 varDecl(hasInitializer(ignoringParenImpCasts(
3015 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003016}
3017
Manuel Klimeke9235692012-07-25 10:02:02 +00003018TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003019 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3020 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003021 implicitCastExpr(
3022 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003023}
3024
Manuel Klimeke9235692012-07-25 10:02:02 +00003025TEST(HasSourceExpression, MatchesExplicitCasts) {
3026 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003027 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003028 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003029 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003030}
3031
Manuel Klimek04616e42012-07-06 05:48:52 +00003032TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003033 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003034}
3035
3036TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003037 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003038}
3039
3040TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003041 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003042}
3043
3044TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003045 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003046}
3047
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003048TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3049 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3050 "const Foo f = Foo();",
3051 varDecl(hasInitializer(exprWithCleanups()))));
3052 EXPECT_FALSE(matches("struct Foo { };"
3053 "const Foo f = Foo();",
3054 varDecl(hasInitializer(exprWithCleanups()))));
3055}
3056
Daniel Jasper1dad1832012-07-10 20:20:19 +00003057TEST(InitListExpression, MatchesInitListExpression) {
3058 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3059 initListExpr(hasType(asString("int [2]")))));
3060 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003061 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003062}
3063
3064TEST(UsingDeclaration, MatchesUsingDeclarations) {
3065 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3066 usingDecl()));
3067}
3068
3069TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3070 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3071 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3072}
3073
3074TEST(UsingDeclaration, MatchesSpecificTarget) {
3075 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3076 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003077 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003078 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3079 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003080 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003081}
3082
3083TEST(UsingDeclaration, ThroughUsingDeclaration) {
3084 EXPECT_TRUE(matches(
3085 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003086 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003087 EXPECT_TRUE(notMatches(
3088 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003089 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003090}
3091
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003092TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3093 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3094 usingDirectiveDecl()));
3095 EXPECT_FALSE(
3096 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3097}
3098
Sam Panzerd624bfb2012-08-16 17:20:59 +00003099TEST(SingleDecl, IsSingleDecl) {
3100 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003101 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003102 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3103 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3104 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3105 SingleDeclStmt));
3106}
3107
3108TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003109 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003110
3111 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003112 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003113 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003114 declStmt(containsDeclaration(0, MatchesInit),
3115 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003116 unsigned WrongIndex = 42;
3117 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003118 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003119 MatchesInit))));
3120}
3121
3122TEST(DeclCount, DeclCountIsCorrect) {
3123 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003124 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003125 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003126 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003127 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003128 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003129}
3130
Manuel Klimek04616e42012-07-06 05:48:52 +00003131TEST(While, MatchesWhileLoops) {
3132 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3133 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3134 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3135}
3136
3137TEST(Do, MatchesDoLoops) {
3138 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3139 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3140}
3141
3142TEST(Do, DoesNotMatchWhileLoops) {
3143 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3144}
3145
3146TEST(SwitchCase, MatchesCase) {
3147 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3148 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3149 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3150 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3151}
3152
Daniel Jasper87c3d362012-09-20 14:12:57 +00003153TEST(SwitchCase, MatchesSwitch) {
3154 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3155 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3156 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3157 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3158}
3159
Peter Collingbourne3154a102013-05-10 11:52:02 +00003160TEST(SwitchCase, MatchesEachCase) {
3161 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3162 switchStmt(forEachSwitchCase(caseStmt()))));
3163 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3164 switchStmt(forEachSwitchCase(caseStmt()))));
3165 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3166 switchStmt(forEachSwitchCase(caseStmt()))));
3167 EXPECT_TRUE(notMatches(
3168 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3169 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3170 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3171 switchStmt(forEachSwitchCase(
3172 caseStmt(hasCaseConstant(integerLiteral()))))));
3173 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3174 switchStmt(forEachSwitchCase(
3175 caseStmt(hasCaseConstant(integerLiteral()))))));
3176 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3177 switchStmt(forEachSwitchCase(
3178 caseStmt(hasCaseConstant(integerLiteral()))))));
3179 EXPECT_TRUE(matchAndVerifyResultTrue(
3180 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3181 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3182 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3183}
3184
Manuel Klimekba46fc02013-07-19 11:50:54 +00003185TEST(ForEachConstructorInitializer, MatchesInitializers) {
3186 EXPECT_TRUE(matches(
3187 "struct X { X() : i(42), j(42) {} int i, j; };",
3188 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3189}
3190
Daniel Jasper87c3d362012-09-20 14:12:57 +00003191TEST(ExceptionHandling, SimpleCases) {
3192 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3193 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3194 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3195 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3196 throwExpr()));
3197 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3198 throwExpr()));
3199}
3200
Manuel Klimek04616e42012-07-06 05:48:52 +00003201TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3202 EXPECT_TRUE(notMatches(
3203 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003204 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003205 EXPECT_TRUE(notMatches(
3206 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003207 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003208}
3209
3210TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3211 EXPECT_TRUE(matches(
3212 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003213 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003214}
3215
3216TEST(ForEach, BindsOneNode) {
3217 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003218 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003219 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003220}
3221
3222TEST(ForEach, BindsMultipleNodes) {
3223 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003224 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003225 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003226}
3227
3228TEST(ForEach, BindsRecursiveCombinations) {
3229 EXPECT_TRUE(matchAndVerifyResultTrue(
3230 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003231 recordDecl(hasName("C"),
3232 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003233 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003234}
3235
3236TEST(ForEachDescendant, BindsOneNode) {
3237 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003238 recordDecl(hasName("C"),
3239 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003240 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003241}
3242
Daniel Jasper94a56852012-11-16 18:39:22 +00003243TEST(ForEachDescendant, NestedForEachDescendant) {
3244 DeclarationMatcher m = recordDecl(
3245 isDefinition(), decl().bind("x"), hasName("C"));
3246 EXPECT_TRUE(matchAndVerifyResultTrue(
3247 "class A { class B { class C {}; }; };",
3248 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3249 new VerifyIdIsBoundTo<Decl>("x", "C")));
3250
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003251 // Check that a partial match of 'm' that binds 'x' in the
3252 // first part of anyOf(m, anything()) will not overwrite the
3253 // binding created by the earlier binding in the hasDescendant.
3254 EXPECT_TRUE(matchAndVerifyResultTrue(
3255 "class A { class B { class C {}; }; };",
3256 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3257 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003258}
3259
Manuel Klimek04616e42012-07-06 05:48:52 +00003260TEST(ForEachDescendant, BindsMultipleNodes) {
3261 EXPECT_TRUE(matchAndVerifyResultTrue(
3262 "class C { class D { int x; int y; }; "
3263 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003264 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003265 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003266}
3267
3268TEST(ForEachDescendant, BindsRecursiveCombinations) {
3269 EXPECT_TRUE(matchAndVerifyResultTrue(
3270 "class C { class D { "
3271 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003272 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3273 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003274 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003275}
3276
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003277TEST(ForEachDescendant, BindsCombinations) {
3278 EXPECT_TRUE(matchAndVerifyResultTrue(
3279 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3280 "(true) {} }",
3281 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3282 forEachDescendant(whileStmt().bind("while"))),
3283 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3284}
3285
3286TEST(Has, DoesNotDeleteBindings) {
3287 EXPECT_TRUE(matchAndVerifyResultTrue(
3288 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3289 new VerifyIdIsBoundTo<Decl>("x", 1)));
3290}
3291
3292TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3293 // Those matchers cover all the cases where an inner matcher is called
3294 // and there is not a 1:1 relationship between the match of the outer
3295 // matcher and the match of the inner matcher.
3296 // The pattern to look for is:
3297 // ... return InnerMatcher.matches(...); ...
3298 // In which case no special handling is needed.
3299 //
3300 // On the other hand, if there are multiple alternative matches
3301 // (for example forEach*) or matches might be discarded (for example has*)
3302 // the implementation must make sure that the discarded matches do not
3303 // affect the bindings.
3304 // When new such matchers are added, add a test here that:
3305 // - matches a simple node, and binds it as the first thing in the matcher:
3306 // recordDecl(decl().bind("x"), hasName("X")))
3307 // - uses the matcher under test afterwards in a way that not the first
3308 // alternative is matched; for anyOf, that means the first branch
3309 // would need to return false; for hasAncestor, it means that not
3310 // the direct parent matches the inner matcher.
3311
3312 EXPECT_TRUE(matchAndVerifyResultTrue(
3313 "class X { int y; };",
3314 recordDecl(
3315 recordDecl().bind("x"), hasName("::X"),
3316 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3317 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3318 EXPECT_TRUE(matchAndVerifyResultTrue(
3319 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3320 anyOf(unless(anything()), anything())),
3321 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3322 EXPECT_TRUE(matchAndVerifyResultTrue(
3323 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3324 classTemplateSpecializationDecl(
3325 decl().bind("x"),
3326 hasAnyTemplateArgument(refersToType(asString("int")))),
3327 new VerifyIdIsBoundTo<Decl>("x", 1)));
3328 EXPECT_TRUE(matchAndVerifyResultTrue(
3329 "class X { void f(); void g(); };",
3330 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3331 new VerifyIdIsBoundTo<Decl>("x", 1)));
3332 EXPECT_TRUE(matchAndVerifyResultTrue(
3333 "class X { X() : a(1), b(2) {} double a; int b; };",
3334 recordDecl(decl().bind("x"),
3335 has(constructorDecl(
3336 hasAnyConstructorInitializer(forField(hasName("b")))))),
3337 new VerifyIdIsBoundTo<Decl>("x", 1)));
3338 EXPECT_TRUE(matchAndVerifyResultTrue(
3339 "void x(int, int) { x(0, 42); }",
3340 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3341 new VerifyIdIsBoundTo<Expr>("x", 1)));
3342 EXPECT_TRUE(matchAndVerifyResultTrue(
3343 "void x(int, int y) {}",
3344 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3345 new VerifyIdIsBoundTo<Decl>("x", 1)));
3346 EXPECT_TRUE(matchAndVerifyResultTrue(
3347 "void x() { return; if (true) {} }",
3348 functionDecl(decl().bind("x"),
3349 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3350 new VerifyIdIsBoundTo<Decl>("x", 1)));
3351 EXPECT_TRUE(matchAndVerifyResultTrue(
3352 "namespace X { void b(int); void b(); }"
3353 "using X::b;",
3354 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3355 functionDecl(parameterCountIs(1))))),
3356 new VerifyIdIsBoundTo<Decl>("x", 1)));
3357 EXPECT_TRUE(matchAndVerifyResultTrue(
3358 "class A{}; class B{}; class C : B, A {};",
3359 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3360 new VerifyIdIsBoundTo<Decl>("x", 1)));
3361 EXPECT_TRUE(matchAndVerifyResultTrue(
3362 "class A{}; typedef A B; typedef A C; typedef A D;"
3363 "class E : A {};",
3364 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3365 new VerifyIdIsBoundTo<Decl>("x", 1)));
3366 EXPECT_TRUE(matchAndVerifyResultTrue(
3367 "class A { class B { void f() {} }; };",
3368 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3369 new VerifyIdIsBoundTo<Decl>("x", 1)));
3370 EXPECT_TRUE(matchAndVerifyResultTrue(
3371 "template <typename T> struct A { struct B {"
3372 " void f() { if(true) {} }"
3373 "}; };"
3374 "void t() { A<int>::B b; b.f(); }",
3375 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3376 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3377 EXPECT_TRUE(matchAndVerifyResultTrue(
3378 "class A {};",
3379 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3380 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003381 EXPECT_TRUE(matchAndVerifyResultTrue(
3382 "class A { A() : s(), i(42) {} const char *s; int i; };",
3383 constructorDecl(hasName("::A::A"), decl().bind("x"),
3384 forEachConstructorInitializer(forField(hasName("i")))),
3385 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003386}
3387
Daniel Jasper33806cd2012-11-11 22:14:55 +00003388TEST(ForEachDescendant, BindsCorrectNodes) {
3389 EXPECT_TRUE(matchAndVerifyResultTrue(
3390 "class C { void f(); int i; };",
3391 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3392 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3393 EXPECT_TRUE(matchAndVerifyResultTrue(
3394 "class C { void f() {} int i; };",
3395 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3396 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3397}
3398
Manuel Klimekabf43712013-02-04 10:59:20 +00003399TEST(FindAll, BindsNodeOnMatch) {
3400 EXPECT_TRUE(matchAndVerifyResultTrue(
3401 "class A {};",
3402 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3403 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3404}
3405
3406TEST(FindAll, BindsDescendantNodeOnMatch) {
3407 EXPECT_TRUE(matchAndVerifyResultTrue(
3408 "class A { int a; int b; };",
3409 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3410 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3411}
3412
3413TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3414 EXPECT_TRUE(matchAndVerifyResultTrue(
3415 "class A { int a; int b; };",
3416 recordDecl(hasName("::A"),
3417 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3418 fieldDecl().bind("v"))))),
3419 new VerifyIdIsBoundTo<Decl>("v", 3)));
3420
3421 EXPECT_TRUE(matchAndVerifyResultTrue(
3422 "class A { class B {}; class C {}; };",
3423 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3424 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3425}
3426
Manuel Klimek88b95872013-02-04 09:42:38 +00003427TEST(EachOf, TriggersForEachMatch) {
3428 EXPECT_TRUE(matchAndVerifyResultTrue(
3429 "class A { int a; int b; };",
3430 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3431 has(fieldDecl(hasName("b")).bind("v")))),
3432 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3433}
3434
3435TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3436 EXPECT_TRUE(matchAndVerifyResultTrue(
3437 "class A { int a; int c; };",
3438 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3439 has(fieldDecl(hasName("b")).bind("v")))),
3440 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3441 EXPECT_TRUE(matchAndVerifyResultTrue(
3442 "class A { int c; int b; };",
3443 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3444 has(fieldDecl(hasName("b")).bind("v")))),
3445 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3446 EXPECT_TRUE(notMatches(
3447 "class A { int c; int d; };",
3448 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3449 has(fieldDecl(hasName("b")).bind("v"))))));
3450}
Manuel Klimek04616e42012-07-06 05:48:52 +00003451
3452TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3453 // Make sure that we can both match the class by name (::X) and by the type
3454 // the template was instantiated with (via a field).
3455
3456 EXPECT_TRUE(matches(
3457 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003458 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003459
3460 EXPECT_TRUE(matches(
3461 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003462 recordDecl(isTemplateInstantiation(), hasDescendant(
3463 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003464}
3465
3466TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3467 EXPECT_TRUE(matches(
3468 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003469 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003470 isTemplateInstantiation())));
3471}
3472
3473TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3474 EXPECT_TRUE(matches(
3475 "template <typename T> class X { T t; }; class A {};"
3476 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003477 recordDecl(isTemplateInstantiation(), hasDescendant(
3478 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003479}
3480
3481TEST(IsTemplateInstantiation,
3482 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3483 EXPECT_TRUE(matches(
3484 "template <typename T> class X {};"
3485 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003486 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003487}
3488
3489TEST(IsTemplateInstantiation,
3490 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3491 EXPECT_TRUE(matches(
3492 "class A {};"
3493 "class X {"
3494 " template <typename U> class Y { U u; };"
3495 " Y<A> y;"
3496 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003497 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003498}
3499
3500TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3501 // FIXME: Figure out whether this makes sense. It doesn't affect the
3502 // normal use case as long as the uppermost instantiation always is marked
3503 // as template instantiation, but it might be confusing as a predicate.
3504 EXPECT_TRUE(matches(
3505 "class A {};"
3506 "template <typename T> class X {"
3507 " template <typename U> class Y { U u; };"
3508 " Y<T> y;"
3509 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003510 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003511}
3512
3513TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3514 EXPECT_TRUE(notMatches(
3515 "template <typename T> class X {}; class A {};"
3516 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003517 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003518}
3519
3520TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3521 EXPECT_TRUE(notMatches(
3522 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003523 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003524}
3525
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003526TEST(IsInstantiated, MatchesInstantiation) {
3527 EXPECT_TRUE(
3528 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3529 recordDecl(isInstantiated())));
3530}
3531
3532TEST(IsInstantiated, NotMatchesDefinition) {
3533 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3534 recordDecl(isInstantiated())));
3535}
3536
3537TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3538 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3539 "class Y { A<int> a; }; Y y;",
3540 declStmt(isInTemplateInstantiation())));
3541}
3542
3543TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3544 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3545 declStmt(isInTemplateInstantiation())));
3546}
3547
3548TEST(IsInstantiated, MatchesFunctionInstantiation) {
3549 EXPECT_TRUE(
3550 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3551 functionDecl(isInstantiated())));
3552}
3553
3554TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3555 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3556 varDecl(isInstantiated())));
3557}
3558
3559TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3560 EXPECT_TRUE(
3561 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3562 declStmt(isInTemplateInstantiation())));
3563}
3564
3565TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3566 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3567 declStmt(isInTemplateInstantiation())));
3568}
3569
3570TEST(IsInTemplateInstantiation, Sharing) {
3571 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3572 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3573 // and makes the matcher behave in non-obvious ways.
3574 EXPECT_TRUE(notMatches(
3575 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3576 Matcher));
3577 EXPECT_TRUE(matches(
3578 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3579 Matcher));
3580}
3581
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003582TEST(IsExplicitTemplateSpecialization,
3583 DoesNotMatchPrimaryTemplate) {
3584 EXPECT_TRUE(notMatches(
3585 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003586 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003587 EXPECT_TRUE(notMatches(
3588 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003589 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003590}
3591
3592TEST(IsExplicitTemplateSpecialization,
3593 DoesNotMatchExplicitTemplateInstantiations) {
3594 EXPECT_TRUE(notMatches(
3595 "template <typename T> class X {};"
3596 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003597 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003598 EXPECT_TRUE(notMatches(
3599 "template <typename T> void f(T t) {}"
3600 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003601 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003602}
3603
3604TEST(IsExplicitTemplateSpecialization,
3605 DoesNotMatchImplicitTemplateInstantiations) {
3606 EXPECT_TRUE(notMatches(
3607 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003608 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003609 EXPECT_TRUE(notMatches(
3610 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003611 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003612}
3613
3614TEST(IsExplicitTemplateSpecialization,
3615 MatchesExplicitTemplateSpecializations) {
3616 EXPECT_TRUE(matches(
3617 "template <typename T> class X {};"
3618 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003619 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003620 EXPECT_TRUE(matches(
3621 "template <typename T> void f(T t) {}"
3622 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003623 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003624}
3625
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003626TEST(HasAncenstor, MatchesDeclarationAncestors) {
3627 EXPECT_TRUE(matches(
3628 "class A { class B { class C {}; }; };",
3629 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3630}
3631
3632TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3633 EXPECT_TRUE(notMatches(
3634 "class A { class B { class C {}; }; };",
3635 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3636}
3637
3638TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3639 EXPECT_TRUE(matches(
3640 "class A { class B { void f() { C c; } class C {}; }; };",
3641 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3642 hasAncestor(recordDecl(hasName("A"))))))));
3643}
3644
3645TEST(HasAncenstor, MatchesStatementAncestors) {
3646 EXPECT_TRUE(matches(
3647 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003648 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003649}
3650
3651TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3652 EXPECT_TRUE(matches(
3653 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003654 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003655}
3656
3657TEST(HasAncestor, BindsRecursiveCombinations) {
3658 EXPECT_TRUE(matchAndVerifyResultTrue(
3659 "class C { class D { class E { class F { int y; }; }; }; };",
3660 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003661 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003662}
3663
3664TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3665 EXPECT_TRUE(matchAndVerifyResultTrue(
3666 "class C { class D { class E { class F { int y; }; }; }; };",
3667 fieldDecl(hasAncestor(
3668 decl(
3669 hasDescendant(recordDecl(isDefinition(),
3670 hasAncestor(recordDecl())))
3671 ).bind("d")
3672 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003673 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003674}
3675
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003676TEST(HasAncestor, MatchesClosestAncestor) {
3677 EXPECT_TRUE(matchAndVerifyResultTrue(
3678 "template <typename T> struct C {"
3679 " void f(int) {"
3680 " struct I { void g(T) { int x; } } i; i.g(42);"
3681 " }"
3682 "};"
3683 "template struct C<int>;",
3684 varDecl(hasName("x"),
3685 hasAncestor(functionDecl(hasParameter(
3686 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3687 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3688}
3689
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003690TEST(HasAncestor, MatchesInTemplateInstantiations) {
3691 EXPECT_TRUE(matches(
3692 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3693 "A<int>::B::C a;",
3694 fieldDecl(hasType(asString("int")),
3695 hasAncestor(recordDecl(hasName("A"))))));
3696}
3697
3698TEST(HasAncestor, MatchesInImplicitCode) {
3699 EXPECT_TRUE(matches(
3700 "struct X {}; struct A { A() {} X x; };",
3701 constructorDecl(
3702 hasAnyConstructorInitializer(withInitializer(expr(
3703 hasAncestor(recordDecl(hasName("A")))))))));
3704}
3705
Daniel Jasper632aea92012-10-22 16:26:51 +00003706TEST(HasParent, MatchesOnlyParent) {
3707 EXPECT_TRUE(matches(
3708 "void f() { if (true) { int x = 42; } }",
3709 compoundStmt(hasParent(ifStmt()))));
3710 EXPECT_TRUE(notMatches(
3711 "void f() { for (;;) { int x = 42; } }",
3712 compoundStmt(hasParent(ifStmt()))));
3713 EXPECT_TRUE(notMatches(
3714 "void f() { if (true) for (;;) { int x = 42; } }",
3715 compoundStmt(hasParent(ifStmt()))));
3716}
3717
Manuel Klimekc844a462012-12-06 14:42:48 +00003718TEST(HasAncestor, MatchesAllAncestors) {
3719 EXPECT_TRUE(matches(
3720 "template <typename T> struct C { static void f() { 42; } };"
3721 "void t() { C<int>::f(); }",
3722 integerLiteral(
3723 equals(42),
3724 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3725 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3726}
3727
3728TEST(HasParent, MatchesAllParents) {
3729 EXPECT_TRUE(matches(
3730 "template <typename T> struct C { static void f() { 42; } };"
3731 "void t() { C<int>::f(); }",
3732 integerLiteral(
3733 equals(42),
3734 hasParent(compoundStmt(hasParent(functionDecl(
3735 hasParent(recordDecl(isTemplateInstantiation())))))))));
3736 EXPECT_TRUE(matches(
3737 "template <typename T> struct C { static void f() { 42; } };"
3738 "void t() { C<int>::f(); }",
3739 integerLiteral(
3740 equals(42),
3741 hasParent(compoundStmt(hasParent(functionDecl(
3742 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3743 EXPECT_TRUE(matches(
3744 "template <typename T> struct C { static void f() { 42; } };"
3745 "void t() { C<int>::f(); }",
3746 integerLiteral(equals(42),
3747 hasParent(compoundStmt(allOf(
3748 hasParent(functionDecl(
3749 hasParent(recordDecl(isTemplateInstantiation())))),
3750 hasParent(functionDecl(hasParent(recordDecl(
3751 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003752 EXPECT_TRUE(
3753 notMatches("template <typename T> struct C { static void f() {} };"
3754 "void t() { C<int>::f(); }",
3755 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003756}
3757
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003758TEST(HasParent, NoDuplicateParents) {
3759 class HasDuplicateParents : public BoundNodesCallback {
3760 public:
3761 bool run(const BoundNodes *Nodes) override { return false; }
3762 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3763 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3764 std::set<const void *> Parents;
3765 for (const auto &Parent : Context->getParents(*Node)) {
3766 if (!Parents.insert(Parent.getMemoizationData()).second) {
3767 return true;
3768 }
3769 }
3770 return false;
3771 }
3772 };
3773 EXPECT_FALSE(matchAndVerifyResultTrue(
3774 "template <typename T> int Foo() { return 1 + 2; }\n"
3775 "int x = Foo<int>() + Foo<unsigned>();",
3776 stmt().bind("node"), new HasDuplicateParents()));
3777}
3778
Daniel Jasper516b02e2012-10-17 08:52:59 +00003779TEST(TypeMatching, MatchesTypes) {
3780 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3781}
3782
3783TEST(TypeMatching, MatchesArrayTypes) {
3784 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3785 EXPECT_TRUE(matches("int a[42];", arrayType()));
3786 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3787
3788 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3789 arrayType(hasElementType(builtinType()))));
3790
3791 EXPECT_TRUE(matches(
3792 "int const a[] = { 2, 3 };",
3793 qualType(arrayType(hasElementType(builtinType())))));
3794 EXPECT_TRUE(matches(
3795 "int const a[] = { 2, 3 };",
3796 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3797 EXPECT_TRUE(matches(
3798 "typedef const int T; T x[] = { 1, 2 };",
3799 qualType(isConstQualified(), arrayType())));
3800
3801 EXPECT_TRUE(notMatches(
3802 "int a[] = { 2, 3 };",
3803 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3804 EXPECT_TRUE(notMatches(
3805 "int a[] = { 2, 3 };",
3806 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3807 EXPECT_TRUE(notMatches(
3808 "int const a[] = { 2, 3 };",
3809 qualType(arrayType(hasElementType(builtinType())),
3810 unless(isConstQualified()))));
3811
3812 EXPECT_TRUE(matches("int a[2];",
3813 constantArrayType(hasElementType(builtinType()))));
3814 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3815}
3816
3817TEST(TypeMatching, MatchesComplexTypes) {
3818 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3819 EXPECT_TRUE(matches(
3820 "_Complex float f;",
3821 complexType(hasElementType(builtinType()))));
3822 EXPECT_TRUE(notMatches(
3823 "_Complex float f;",
3824 complexType(hasElementType(isInteger()))));
3825}
3826
3827TEST(TypeMatching, MatchesConstantArrayTypes) {
3828 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3829 EXPECT_TRUE(notMatches(
3830 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3831 constantArrayType(hasElementType(builtinType()))));
3832
3833 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3834 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3835 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3836}
3837
3838TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3839 EXPECT_TRUE(matches(
3840 "template <typename T, int Size> class array { T data[Size]; };",
3841 dependentSizedArrayType()));
3842 EXPECT_TRUE(notMatches(
3843 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3844 dependentSizedArrayType()));
3845}
3846
3847TEST(TypeMatching, MatchesIncompleteArrayType) {
3848 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3849 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3850
3851 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3852 incompleteArrayType()));
3853}
3854
3855TEST(TypeMatching, MatchesVariableArrayType) {
3856 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3857 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3858
3859 EXPECT_TRUE(matches(
3860 "void f(int b) { int a[b]; }",
3861 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3862 varDecl(hasName("b")))))))));
3863}
3864
3865TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003866 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3867 llvm::Triple::Win32) {
3868 // FIXME: Make this work for MSVC.
3869 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003870
David Majnemer197e2102014-03-05 06:32:38 +00003871 EXPECT_TRUE(matches("_Atomic(int) i;",
3872 atomicType(hasValueType(isInteger()))));
3873 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3874 atomicType(hasValueType(isInteger()))));
3875 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003876}
3877
3878TEST(TypeMatching, MatchesAutoTypes) {
3879 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3880 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3881 autoType()));
3882
Richard Smith061f1e22013-04-30 21:23:01 +00003883 // FIXME: Matching against the type-as-written can't work here, because the
3884 // type as written was not deduced.
3885 //EXPECT_TRUE(matches("auto a = 1;",
3886 // autoType(hasDeducedType(isInteger()))));
3887 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3888 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003889}
3890
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00003891TEST(TypeMatching, MatchesFunctionTypes) {
3892 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3893 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3894}
3895
Edwin Vaneec074802013-04-01 18:33:34 +00003896TEST(TypeMatching, MatchesParenType) {
3897 EXPECT_TRUE(
3898 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3899 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3900
3901 EXPECT_TRUE(matches(
3902 "int (*ptr_to_func)(int);",
3903 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3904 EXPECT_TRUE(notMatches(
3905 "int (*ptr_to_array)[4];",
3906 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3907}
3908
Daniel Jasper516b02e2012-10-17 08:52:59 +00003909TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003910 // FIXME: Reactive when these tests can be more specific (not matching
3911 // implicit code on certain platforms), likely when we have hasDescendant for
3912 // Types/TypeLocs.
3913 //EXPECT_TRUE(matchAndVerifyResultTrue(
3914 // "int* a;",
3915 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3916 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3917 //EXPECT_TRUE(matchAndVerifyResultTrue(
3918 // "int* a;",
3919 // pointerTypeLoc().bind("loc"),
3920 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003921 EXPECT_TRUE(matches(
3922 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003923 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003924 EXPECT_TRUE(matches(
3925 "int** a;",
3926 loc(pointerType(pointee(pointerType())))));
3927 EXPECT_TRUE(matches(
3928 "int* b; int* * const a = &b;",
3929 loc(qualType(isConstQualified(), pointerType()))));
3930
3931 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00003932 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3933 hasType(blockPointerType()))));
3934 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3935 hasType(memberPointerType()))));
3936 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3937 hasType(pointerType()))));
3938 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3939 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003940 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3941 hasType(lValueReferenceType()))));
3942 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3943 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003944
Daniel Jasper7943eb52012-10-17 13:35:36 +00003945 Fragment = "int *ptr;";
3946 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3947 hasType(blockPointerType()))));
3948 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3949 hasType(memberPointerType()))));
3950 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3951 hasType(pointerType()))));
3952 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3953 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003954
Daniel Jasper7943eb52012-10-17 13:35:36 +00003955 Fragment = "int a; int &ref = a;";
3956 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3957 hasType(blockPointerType()))));
3958 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3959 hasType(memberPointerType()))));
3960 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3961 hasType(pointerType()))));
3962 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3963 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003964 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3965 hasType(lValueReferenceType()))));
3966 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3967 hasType(rValueReferenceType()))));
3968
3969 Fragment = "int &&ref = 2;";
3970 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3971 hasType(blockPointerType()))));
3972 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3973 hasType(memberPointerType()))));
3974 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3975 hasType(pointerType()))));
3976 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3977 hasType(referenceType()))));
3978 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3979 hasType(lValueReferenceType()))));
3980 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3981 hasType(rValueReferenceType()))));
3982}
3983
3984TEST(TypeMatching, AutoRefTypes) {
3985 std::string Fragment = "auto a = 1;"
3986 "auto b = a;"
3987 "auto &c = a;"
3988 "auto &&d = c;"
3989 "auto &&e = 2;";
3990 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
3991 hasType(referenceType()))));
3992 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
3993 hasType(referenceType()))));
3994 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3995 hasType(referenceType()))));
3996 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3997 hasType(lValueReferenceType()))));
3998 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
3999 hasType(rValueReferenceType()))));
4000 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4001 hasType(referenceType()))));
4002 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4003 hasType(lValueReferenceType()))));
4004 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4005 hasType(rValueReferenceType()))));
4006 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4007 hasType(referenceType()))));
4008 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4009 hasType(lValueReferenceType()))));
4010 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4011 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004012}
4013
4014TEST(TypeMatching, PointeeTypes) {
4015 EXPECT_TRUE(matches("int b; int &a = b;",
4016 referenceType(pointee(builtinType()))));
4017 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4018
4019 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004020 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004021
4022 EXPECT_TRUE(matches(
4023 "int const *A;",
4024 pointerType(pointee(isConstQualified(), builtinType()))));
4025 EXPECT_TRUE(notMatches(
4026 "int *A;",
4027 pointerType(pointee(isConstQualified(), builtinType()))));
4028}
4029
4030TEST(TypeMatching, MatchesPointersToConstTypes) {
4031 EXPECT_TRUE(matches("int b; int * const a = &b;",
4032 loc(pointerType())));
4033 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004034 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004035 EXPECT_TRUE(matches(
4036 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004037 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004038 EXPECT_TRUE(matches(
4039 "int b; const int * a = &b;",
4040 pointerType(pointee(builtinType()))));
4041}
4042
4043TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004044 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4045 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004046}
4047
Edwin Vanef901b712013-02-25 14:49:29 +00004048TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004049 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004050 templateSpecializationType()));
4051}
4052
Edwin Vaneb6eae142013-02-25 20:43:32 +00004053TEST(TypeMatching, MatchesRecordType) {
4054 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004055 EXPECT_TRUE(matches("struct S{}; S s;",
4056 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4057 EXPECT_TRUE(notMatches("int i;",
4058 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004059}
4060
4061TEST(TypeMatching, MatchesElaboratedType) {
4062 EXPECT_TRUE(matches(
4063 "namespace N {"
4064 " namespace M {"
4065 " class D {};"
4066 " }"
4067 "}"
4068 "N::M::D d;", elaboratedType()));
4069 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4070 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4071}
4072
4073TEST(ElaboratedTypeNarrowing, hasQualifier) {
4074 EXPECT_TRUE(matches(
4075 "namespace N {"
4076 " namespace M {"
4077 " class D {};"
4078 " }"
4079 "}"
4080 "N::M::D d;",
4081 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4082 EXPECT_TRUE(notMatches(
4083 "namespace M {"
4084 " class D {};"
4085 "}"
4086 "M::D d;",
4087 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004088 EXPECT_TRUE(notMatches(
4089 "struct D {"
4090 "} d;",
4091 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004092}
4093
4094TEST(ElaboratedTypeNarrowing, namesType) {
4095 EXPECT_TRUE(matches(
4096 "namespace N {"
4097 " namespace M {"
4098 " class D {};"
4099 " }"
4100 "}"
4101 "N::M::D d;",
4102 elaboratedType(elaboratedType(namesType(recordType(
4103 hasDeclaration(namedDecl(hasName("D")))))))));
4104 EXPECT_TRUE(notMatches(
4105 "namespace M {"
4106 " class D {};"
4107 "}"
4108 "M::D d;",
4109 elaboratedType(elaboratedType(namesType(typedefType())))));
4110}
4111
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004112TEST(NNS, MatchesNestedNameSpecifiers) {
4113 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4114 nestedNameSpecifier()));
4115 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4116 nestedNameSpecifier()));
4117 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4118 nestedNameSpecifier()));
4119
4120 EXPECT_TRUE(matches(
4121 "struct A { static void f() {} }; void g() { A::f(); }",
4122 nestedNameSpecifier()));
4123 EXPECT_TRUE(notMatches(
4124 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4125 nestedNameSpecifier()));
4126}
4127
Daniel Jasper87c3d362012-09-20 14:12:57 +00004128TEST(NullStatement, SimpleCases) {
4129 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4130 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4131}
4132
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004133TEST(NNS, MatchesTypes) {
4134 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4135 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4136 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4137 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4138 Matcher));
4139 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4140}
4141
4142TEST(NNS, MatchesNamespaceDecls) {
4143 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4144 specifiesNamespace(hasName("ns")));
4145 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4146 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4147 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4148}
4149
4150TEST(NNS, BindsNestedNameSpecifiers) {
4151 EXPECT_TRUE(matchAndVerifyResultTrue(
4152 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4153 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4154 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4155}
4156
4157TEST(NNS, BindsNestedNameSpecifierLocs) {
4158 EXPECT_TRUE(matchAndVerifyResultTrue(
4159 "namespace ns { struct B {}; } ns::B b;",
4160 loc(nestedNameSpecifier()).bind("loc"),
4161 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4162}
4163
4164TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4165 EXPECT_TRUE(matches(
4166 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4167 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4168 EXPECT_TRUE(matches(
4169 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004170 nestedNameSpecifierLoc(hasPrefix(
4171 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004172}
4173
Daniel Jasper6fc34332012-10-30 15:42:00 +00004174TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4175 std::string Fragment =
4176 "namespace a { struct A { struct B { struct C {}; }; }; };"
4177 "void f() { a::A::B::C c; }";
4178 EXPECT_TRUE(matches(
4179 Fragment,
4180 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4181 hasDescendant(nestedNameSpecifier(
4182 specifiesNamespace(hasName("a")))))));
4183 EXPECT_TRUE(notMatches(
4184 Fragment,
4185 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4186 has(nestedNameSpecifier(
4187 specifiesNamespace(hasName("a")))))));
4188 EXPECT_TRUE(matches(
4189 Fragment,
4190 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4191 has(nestedNameSpecifier(
4192 specifiesNamespace(hasName("a")))))));
4193
4194 // Not really useful because a NestedNameSpecifier can af at most one child,
4195 // but to complete the interface.
4196 EXPECT_TRUE(matchAndVerifyResultTrue(
4197 Fragment,
4198 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4199 forEach(nestedNameSpecifier().bind("x"))),
4200 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4201}
4202
4203TEST(NNS, NestedNameSpecifiersAsDescendants) {
4204 std::string Fragment =
4205 "namespace a { struct A { struct B { struct C {}; }; }; };"
4206 "void f() { a::A::B::C c; }";
4207 EXPECT_TRUE(matches(
4208 Fragment,
4209 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4210 asString("struct a::A")))))));
4211 EXPECT_TRUE(matchAndVerifyResultTrue(
4212 Fragment,
4213 functionDecl(hasName("f"),
4214 forEachDescendant(nestedNameSpecifier().bind("x"))),
4215 // Nested names: a, a::A and a::A::B.
4216 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4217}
4218
4219TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4220 std::string Fragment =
4221 "namespace a { struct A { struct B { struct C {}; }; }; };"
4222 "void f() { a::A::B::C c; }";
4223 EXPECT_TRUE(matches(
4224 Fragment,
4225 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4226 hasDescendant(loc(nestedNameSpecifier(
4227 specifiesNamespace(hasName("a"))))))));
4228 EXPECT_TRUE(notMatches(
4229 Fragment,
4230 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4231 has(loc(nestedNameSpecifier(
4232 specifiesNamespace(hasName("a"))))))));
4233 EXPECT_TRUE(matches(
4234 Fragment,
4235 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4236 has(loc(nestedNameSpecifier(
4237 specifiesNamespace(hasName("a"))))))));
4238
4239 EXPECT_TRUE(matchAndVerifyResultTrue(
4240 Fragment,
4241 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4242 forEach(nestedNameSpecifierLoc().bind("x"))),
4243 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4244}
4245
4246TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4247 std::string Fragment =
4248 "namespace a { struct A { struct B { struct C {}; }; }; };"
4249 "void f() { a::A::B::C c; }";
4250 EXPECT_TRUE(matches(
4251 Fragment,
4252 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4253 asString("struct a::A"))))))));
4254 EXPECT_TRUE(matchAndVerifyResultTrue(
4255 Fragment,
4256 functionDecl(hasName("f"),
4257 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4258 // Nested names: a, a::A and a::A::B.
4259 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4260}
4261
Manuel Klimek191c0932013-02-01 13:41:35 +00004262template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004263public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004264 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4265 StringRef InnerId)
4266 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004267 }
4268
Manuel Klimek191c0932013-02-01 13:41:35 +00004269 virtual bool run(const BoundNodes *Nodes) { return false; }
4270
Manuel Klimekc2687452012-10-24 14:47:44 +00004271 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4272 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004273 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4274 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004275 }
4276private:
4277 std::string Id;
4278 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004279 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004280};
4281
4282TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004283 EXPECT_TRUE(matchAndVerifyResultTrue(
4284 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4285 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004286 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4287 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004288 EXPECT_TRUE(matchAndVerifyResultFalse(
4289 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4290 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004291 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4292 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004293}
4294
4295TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004296 EXPECT_TRUE(matchAndVerifyResultTrue(
4297 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004298 new VerifyMatchOnNode<clang::Stmt>(
4299 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004300 EXPECT_TRUE(matchAndVerifyResultFalse(
4301 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004302 new VerifyMatchOnNode<clang::Stmt>(
4303 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004304}
4305
4306TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4307 EXPECT_TRUE(matchAndVerifyResultTrue(
4308 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4309 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004310 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004311 EXPECT_TRUE(matchAndVerifyResultFalse(
4312 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4313 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004314 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004315}
4316
Manuel Klimekbee08572013-02-07 12:42:10 +00004317template <typename T>
4318class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4319public:
4320 virtual bool run(const BoundNodes *Nodes) { return false; }
4321
4322 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4323 const T *Node = Nodes->getNodeAs<T>("");
4324 return verify(*Nodes, *Context, Node);
4325 }
4326
4327 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004328 // Use the original typed pointer to verify we can pass pointers to subtypes
4329 // to equalsNode.
4330 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004331 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004332 "", match(stmt(hasParent(
4333 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004334 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004335 }
4336 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004337 // Use the original typed pointer to verify we can pass pointers to subtypes
4338 // to equalsNode.
4339 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004340 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004341 "", match(decl(hasParent(
4342 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004343 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004344 }
4345};
4346
4347TEST(IsEqualTo, MatchesNodesByIdentity) {
4348 EXPECT_TRUE(matchAndVerifyResultTrue(
4349 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004350 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4351 EXPECT_TRUE(matchAndVerifyResultTrue(
4352 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4353 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004354}
4355
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004356class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4357public:
4358 VerifyStartOfTranslationUnit() : Called(false) {}
4359 virtual void run(const MatchFinder::MatchResult &Result) {
4360 EXPECT_TRUE(Called);
4361 }
4362 virtual void onStartOfTranslationUnit() {
4363 Called = true;
4364 }
4365 bool Called;
4366};
4367
4368TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4369 MatchFinder Finder;
4370 VerifyStartOfTranslationUnit VerifyCallback;
4371 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004372 std::unique_ptr<FrontendActionFactory> Factory(
4373 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004374 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4375 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004376
4377 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004378 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004379 ASSERT_TRUE(AST.get());
4380 Finder.matchAST(AST->getASTContext());
4381 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004382}
4383
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004384class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4385public:
4386 VerifyEndOfTranslationUnit() : Called(false) {}
4387 virtual void run(const MatchFinder::MatchResult &Result) {
4388 EXPECT_FALSE(Called);
4389 }
4390 virtual void onEndOfTranslationUnit() {
4391 Called = true;
4392 }
4393 bool Called;
4394};
4395
4396TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4397 MatchFinder Finder;
4398 VerifyEndOfTranslationUnit VerifyCallback;
4399 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004400 std::unique_ptr<FrontendActionFactory> Factory(
4401 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004402 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4403 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004404
4405 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004406 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004407 ASSERT_TRUE(AST.get());
4408 Finder.matchAST(AST->getASTContext());
4409 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004410}
4411
Manuel Klimekbbb75852013-06-20 14:06:32 +00004412TEST(EqualsBoundNodeMatcher, QualType) {
4413 EXPECT_TRUE(matches(
4414 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4415 hasInitializer(ignoringParenImpCasts(
4416 hasType(qualType(equalsBoundNode("type"))))))));
4417 EXPECT_TRUE(notMatches("int i = 1.f;",
4418 varDecl(hasType(qualType().bind("type")),
4419 hasInitializer(ignoringParenImpCasts(hasType(
4420 qualType(equalsBoundNode("type"))))))));
4421}
4422
4423TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4424 EXPECT_TRUE(notMatches(
4425 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4426 hasInitializer(ignoringParenImpCasts(
4427 hasType(qualType(equalsBoundNode("type"))))))));
4428}
4429
4430TEST(EqualsBoundNodeMatcher, Stmt) {
4431 EXPECT_TRUE(
4432 matches("void f() { if(true) {} }",
4433 stmt(allOf(ifStmt().bind("if"),
4434 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4435
4436 EXPECT_TRUE(notMatches(
4437 "void f() { if(true) { if (true) {} } }",
4438 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4439}
4440
4441TEST(EqualsBoundNodeMatcher, Decl) {
4442 EXPECT_TRUE(matches(
4443 "class X { class Y {}; };",
4444 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4445 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4446
4447 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4448 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4449 has(decl(equalsBoundNode("record")))))));
4450}
4451
4452TEST(EqualsBoundNodeMatcher, Type) {
4453 EXPECT_TRUE(matches(
4454 "class X { int a; int b; };",
4455 recordDecl(
4456 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4457 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4458
4459 EXPECT_TRUE(notMatches(
4460 "class X { int a; double b; };",
4461 recordDecl(
4462 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4463 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4464}
4465
4466TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004467 EXPECT_TRUE(matchAndVerifyResultTrue(
4468 "int f() {"
4469 " if (1) {"
4470 " int i = 9;"
4471 " }"
4472 " int j = 10;"
4473 " {"
4474 " float k = 9.0;"
4475 " }"
4476 " return 0;"
4477 "}",
4478 // Look for variable declarations within functions whose type is the same
4479 // as the function return type.
4480 functionDecl(returns(qualType().bind("type")),
4481 forEachDescendant(varDecl(hasType(
4482 qualType(equalsBoundNode("type")))).bind("decl"))),
4483 // Only i and j should match, not k.
4484 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4485}
4486
4487TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4488 EXPECT_TRUE(matchAndVerifyResultTrue(
4489 "void f() {"
4490 " int x;"
4491 " double d;"
4492 " x = d + x - d + x;"
4493 "}",
4494 functionDecl(
4495 hasName("f"), forEachDescendant(varDecl().bind("d")),
4496 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4497 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4498}
4499
Manuel Klimekce68f772014-03-25 14:39:26 +00004500TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4501 EXPECT_TRUE(matchAndVerifyResultTrue(
4502 "struct StringRef { int size() const; const char* data() const; };"
4503 "void f(StringRef v) {"
4504 " v.data();"
4505 "}",
4506 memberCallExpr(
4507 callee(methodDecl(hasName("data"))),
4508 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4509 .bind("var")))),
4510 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4511 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4512 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4513 .bind("data"),
4514 new VerifyIdIsBoundTo<Expr>("data", 1)));
4515
4516 EXPECT_FALSE(matches(
4517 "struct StringRef { int size() const; const char* data() const; };"
4518 "void f(StringRef v) {"
4519 " v.data();"
4520 " v.size();"
4521 "}",
4522 memberCallExpr(
4523 callee(methodDecl(hasName("data"))),
4524 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4525 .bind("var")))),
4526 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4527 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4528 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4529 .bind("data")));
4530}
4531
Manuel Klimek04616e42012-07-06 05:48:52 +00004532} // end namespace ast_matchers
4533} // end namespace clang