blob: 3fbe896a87b4652fa51221d403c9a3d0e4368f2f [file] [log] [blame]
Manuel Klimek04616e42012-07-06 05:48:52 +00001//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher unit tests ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ASTMatchersTest.h"
Benjamin Kramere5015e52012-12-01 17:22:05 +000011#include "clang/AST/PrettyPrinter.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Chandler Carruth320d9662012-12-04 09:45:34 +000013#include "clang/ASTMatchers/ASTMatchers.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000014#include "clang/Tooling/Tooling.h"
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +000015#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000017#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000022#if GTEST_HAS_DEATH_TEST
Manuel Klimek04616e42012-07-06 05:48:52 +000023TEST(HasNameDeathTest, DiesOnEmptyName) {
24 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000025 DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000026 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27 }, "");
28}
29
Daniel Jasper1dad1832012-07-10 20:20:19 +000030TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000032 DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
Daniel Jasper1dad1832012-07-10 20:20:19 +000033 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34 }, "");
35}
36
Manuel Klimek04616e42012-07-06 05:48:52 +000037TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000039 DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000040 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41 }, "");
42}
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000043#endif
Manuel Klimek04616e42012-07-06 05:48:52 +000044
Peter Collingbourne2b9471302013-11-07 22:30:32 +000045TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46 MatchFinder Finder;
Craig Topper416fa342014-06-08 08:38:12 +000047 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50 nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000051
52 // Do not accept non-toplevel matchers.
Craig Topper416fa342014-06-08 08:38:12 +000053 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54 EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000056}
57
Manuel Klimeke9235692012-07-25 10:02:02 +000058TEST(Decl, MatchesDeclarations) {
59 EXPECT_TRUE(notMatches("", decl(usingDecl())));
60 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
61 decl(usingDecl())));
62}
63
Manuel Klimek04616e42012-07-06 05:48:52 +000064TEST(NameableDeclaration, MatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000065 DeclarationMatcher NamedX = namedDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +000066 EXPECT_TRUE(matches("typedef int X;", NamedX));
67 EXPECT_TRUE(matches("int X;", NamedX));
68 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
69 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
70 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
71 EXPECT_TRUE(matches("namespace X { }", NamedX));
Daniel Jasper1dad1832012-07-10 20:20:19 +000072 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
Manuel Klimek04616e42012-07-06 05:48:52 +000073
74 EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
Daniel Jasper1dad1832012-07-10 20:20:19 +000077TEST(NameableDeclaration, REMatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000078 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000079 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
80 EXPECT_TRUE(matches("int Xb;", NamedX));
81 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
82 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
83 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
84 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
85 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
86
87 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
88
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000089 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000090 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
91 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
92
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000093 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000094 EXPECT_TRUE(matches("int abc;", Abc));
95 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
96 EXPECT_TRUE(notMatches("int cab;", Abc));
97 EXPECT_TRUE(matches("int cabc;", Abc));
Manuel Klimeke792efd2012-12-10 07:08:53 +000098
99 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
100 EXPECT_TRUE(matches("int k;", StartsWithK));
101 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
102 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
103 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
104 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000105}
106
Manuel Klimek04616e42012-07-06 05:48:52 +0000107TEST(DeclarationMatcher, MatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000108 DeclarationMatcher ClassMatcher(recordDecl());
Saleem Abdulrasool377066a2014-03-27 22:50:18 +0000109 llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110 if (Triple.getOS() != llvm::Triple::Win32 ||
111 Triple.getEnvironment() != llvm::Triple::MSVC)
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +0000112 EXPECT_FALSE(matches("", ClassMatcher));
113 else
114 // Matches class type_info.
115 EXPECT_TRUE(matches("", ClassMatcher));
Manuel Klimek04616e42012-07-06 05:48:52 +0000116
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000117 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000118 EXPECT_TRUE(matches("class X;", ClassX));
119 EXPECT_TRUE(matches("class X {};", ClassX));
120 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
121 EXPECT_TRUE(notMatches("", ClassX));
122}
123
124TEST(DeclarationMatcher, ClassIsDerived) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000125 DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000126
127 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000128 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
Manuel Klimek04616e42012-07-06 05:48:52 +0000130 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131 EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
Daniel Jasperd6b82cb2012-09-12 21:14:15 +0000133 DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000134
135 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
136 EXPECT_TRUE(matches("class X {};", IsAX));
137 EXPECT_TRUE(matches("class X;", IsAX));
138 EXPECT_TRUE(notMatches("class Y;", IsAX));
139 EXPECT_TRUE(notMatches("", IsAX));
140
Manuel Klimek04616e42012-07-06 05:48:52 +0000141 DeclarationMatcher ZIsDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000142 recordDecl(hasName("Z"), isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000143 EXPECT_TRUE(
144 matches("class X {}; class Y : public X {}; class Z : public Y {};",
145 ZIsDerivedFromX));
146 EXPECT_TRUE(
147 matches("class X {};"
148 "template<class T> class Y : public X {};"
149 "class Z : public Y<int> {};", ZIsDerivedFromX));
150 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
151 ZIsDerivedFromX));
152 EXPECT_TRUE(
153 matches("template<class T> class X {}; "
154 "template<class T> class Z : public X<T> {};",
155 ZIsDerivedFromX));
156 EXPECT_TRUE(
157 matches("template<class T, class U=T> class X {}; "
158 "template<class T> class Z : public X<T> {};",
159 ZIsDerivedFromX));
160 EXPECT_TRUE(
161 notMatches("template<class X> class A { class Z : public X {}; };",
162 ZIsDerivedFromX));
163 EXPECT_TRUE(
164 matches("template<class X> class A { public: class Z : public X {}; }; "
165 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
166 EXPECT_TRUE(
167 matches("template <class T> class X {}; "
168 "template<class Y> class A { class Z : public X<Y> {}; };",
169 ZIsDerivedFromX));
170 EXPECT_TRUE(
171 notMatches("template<template<class T> class X> class A { "
172 " class Z : public X<int> {}; };", ZIsDerivedFromX));
173 EXPECT_TRUE(
174 matches("template<template<class T> class X> class A { "
175 " public: class Z : public X<int> {}; }; "
176 "template<class T> class X {}; void y() { A<X>::Z z; }",
177 ZIsDerivedFromX));
178 EXPECT_TRUE(
179 notMatches("template<class X> class A { class Z : public X::D {}; };",
180 ZIsDerivedFromX));
181 EXPECT_TRUE(
182 matches("template<class X> class A { public: "
183 " class Z : public X::D {}; }; "
184 "class Y { public: class X {}; typedef X D; }; "
185 "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
186 EXPECT_TRUE(
187 matches("class X {}; typedef X Y; class Z : public Y {};",
188 ZIsDerivedFromX));
189 EXPECT_TRUE(
190 matches("template<class T> class Y { typedef typename T::U X; "
191 " class Z : public X {}; };", ZIsDerivedFromX));
192 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
193 ZIsDerivedFromX));
194 EXPECT_TRUE(
195 notMatches("template<class T> class X {}; "
196 "template<class T> class A { class Z : public X<T>::D {}; };",
197 ZIsDerivedFromX));
198 EXPECT_TRUE(
199 matches("template<class T> class X { public: typedef X<T> D; }; "
200 "template<class T> class A { public: "
201 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
202 ZIsDerivedFromX));
203 EXPECT_TRUE(
204 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
205 ZIsDerivedFromX));
206 EXPECT_TRUE(
207 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
208 ZIsDerivedFromX));
209 EXPECT_TRUE(
210 matches("class X {}; class Y : public X {}; "
211 "typedef Y V; typedef V W; class Z : public W {};",
212 ZIsDerivedFromX));
213 EXPECT_TRUE(
214 matches("template<class T, class U> class X {}; "
215 "template<class T> class A { class Z : public X<T, int> {}; };",
216 ZIsDerivedFromX));
217 EXPECT_TRUE(
218 notMatches("template<class X> class D { typedef X A; typedef A B; "
219 " typedef B C; class Z : public C {}; };",
220 ZIsDerivedFromX));
221 EXPECT_TRUE(
222 matches("class X {}; typedef X A; typedef A B; "
223 "class Z : public B {};", ZIsDerivedFromX));
224 EXPECT_TRUE(
225 matches("class X {}; typedef X A; typedef A B; typedef B C; "
226 "class Z : public C {};", ZIsDerivedFromX));
227 EXPECT_TRUE(
228 matches("class U {}; typedef U X; typedef X V; "
229 "class Z : public V {};", ZIsDerivedFromX));
230 EXPECT_TRUE(
231 matches("class Base {}; typedef Base X; "
232 "class Z : public Base {};", ZIsDerivedFromX));
233 EXPECT_TRUE(
234 matches("class Base {}; typedef Base Base2; typedef Base2 X; "
235 "class Z : public Base {};", ZIsDerivedFromX));
236 EXPECT_TRUE(
237 notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
238 "class Z : public Base {};", ZIsDerivedFromX));
239 EXPECT_TRUE(
240 matches("class A {}; typedef A X; typedef A Y; "
241 "class Z : public Y {};", ZIsDerivedFromX));
242 EXPECT_TRUE(
243 notMatches("template <typename T> class Z;"
244 "template <> class Z<void> {};"
245 "template <typename T> class Z : public Z<void> {};",
246 IsDerivedFromX));
247 EXPECT_TRUE(
248 matches("template <typename T> class X;"
249 "template <> class X<void> {};"
250 "template <typename T> class X : public X<void> {};",
251 IsDerivedFromX));
252 EXPECT_TRUE(matches(
253 "class X {};"
254 "template <typename T> class Z;"
255 "template <> class Z<void> {};"
256 "template <typename T> class Z : public Z<void>, public X {};",
257 ZIsDerivedFromX));
Manuel Klimek5472a522012-12-04 13:40:29 +0000258 EXPECT_TRUE(
259 notMatches("template<int> struct X;"
260 "template<int i> struct X : public X<i-1> {};",
261 recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
262 EXPECT_TRUE(matches(
263 "struct A {};"
264 "template<int> struct X;"
265 "template<int i> struct X : public X<i-1> {};"
266 "template<> struct X<0> : public A {};"
267 "struct B : public X<42> {};",
268 recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000269
270 // FIXME: Once we have better matchers for template type matching,
271 // get rid of the Variable(...) matching and match the right template
272 // declarations directly.
273 const char *RecursiveTemplateOneParameter =
274 "class Base1 {}; class Base2 {};"
275 "template <typename T> class Z;"
276 "template <> class Z<void> : public Base1 {};"
277 "template <> class Z<int> : public Base2 {};"
278 "template <> class Z<float> : public Z<void> {};"
279 "template <> class Z<double> : public Z<int> {};"
280 "template <typename T> class Z : public Z<float>, public Z<double> {};"
281 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
282 EXPECT_TRUE(matches(
283 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000284 varDecl(hasName("z_float"),
285 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000286 EXPECT_TRUE(notMatches(
287 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000288 varDecl(hasName("z_float"),
289 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000290 EXPECT_TRUE(matches(
291 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000292 varDecl(hasName("z_char"),
293 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
294 isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000295
296 const char *RecursiveTemplateTwoParameters =
297 "class Base1 {}; class Base2 {};"
298 "template <typename T1, typename T2> class Z;"
299 "template <typename T> class Z<void, T> : public Base1 {};"
300 "template <typename T> class Z<int, T> : public Base2 {};"
301 "template <typename T> class Z<float, T> : public Z<void, T> {};"
302 "template <typename T> class Z<double, T> : public Z<int, T> {};"
303 "template <typename T1, typename T2> class Z : "
304 " public Z<float, T2>, public Z<double, T2> {};"
305 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
306 " Z<char, void> z_char; }";
307 EXPECT_TRUE(matches(
308 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000309 varDecl(hasName("z_float"),
310 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000311 EXPECT_TRUE(notMatches(
312 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000313 varDecl(hasName("z_float"),
314 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000315 EXPECT_TRUE(matches(
316 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000317 varDecl(hasName("z_char"),
318 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
319 isDerivedFrom("Base2")))))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000322 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000325 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000329 recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
Manuel Klimek1863e502013-08-02 21:24:09 +0000330
331 EXPECT_TRUE(matches(
332 "template<typename T> class X {};"
333 "template<typename T> using Z = X<T>;"
334 "template <typename T> class Y : Z<T> {};",
335 recordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000336}
337
Edwin Vane0a4836e2013-03-06 17:02:57 +0000338TEST(DeclarationMatcher, hasMethod) {
339 EXPECT_TRUE(matches("class A { void func(); };",
340 recordDecl(hasMethod(hasName("func")))));
341 EXPECT_TRUE(notMatches("class A { void func(); };",
342 recordDecl(hasMethod(isPublic()))));
343}
344
Daniel Jasper83dafaf2012-09-18 14:17:42 +0000345TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
346 EXPECT_TRUE(matches(
347 "template <typename T> struct A {"
348 " template <typename T2> struct F {};"
349 "};"
350 "template <typename T> struct B : A<T>::template F<T> {};"
351 "B<int> b;",
352 recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
353}
354
Edwin Vaneb6eae142013-02-25 20:43:32 +0000355TEST(DeclarationMatcher, hasDeclContext) {
356 EXPECT_TRUE(matches(
357 "namespace N {"
358 " namespace M {"
359 " class D {};"
360 " }"
361 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000362 recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000363 EXPECT_TRUE(notMatches(
364 "namespace N {"
365 " namespace M {"
366 " class D {};"
367 " }"
368 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000369 recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
370
371 EXPECT_TRUE(matches("namespace {"
372 " namespace M {"
373 " class D {};"
374 " }"
375 "}",
376 recordDecl(hasDeclContext(namespaceDecl(
377 hasName("M"), hasDeclContext(namespaceDecl()))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000378}
379
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000380TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000381 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000382 EXPECT_TRUE(notMatches("class X;", ClassX));
383 EXPECT_TRUE(notMatches("class X {};", ClassX));
384}
385
386TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000387 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000388 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
389 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
390}
391
392TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
393 EXPECT_TRUE(notMatches("template<typename T> class X { };"
394 "template<> class X<int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000395 classTemplateDecl(hasName("X"),
396 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000397}
398
399TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
400 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
401 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000402 classTemplateDecl(hasName("X"),
403 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000404}
405
Daniel Jasper4e566c42012-07-12 08:50:38 +0000406TEST(AllOf, AllOverloadsWork) {
407 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000408 "struct T { };"
409 "int f(int, T*, int, int);"
410 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000411 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000412 callExpr(allOf(callee(functionDecl(hasName("f"))),
413 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000414 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000415 callExpr(allOf(callee(functionDecl(hasName("f"))),
416 hasArgument(0, declRefExpr(to(varDecl()))),
417 hasArgument(1, hasType(pointsTo(
418 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000419 EXPECT_TRUE(matches(Program,
420 callExpr(allOf(callee(functionDecl(hasName("f"))),
421 hasArgument(0, declRefExpr(to(varDecl()))),
422 hasArgument(1, hasType(pointsTo(
423 recordDecl(hasName("T"))))),
424 hasArgument(2, integerLiteral(equals(3)))))));
425 EXPECT_TRUE(matches(Program,
426 callExpr(allOf(callee(functionDecl(hasName("f"))),
427 hasArgument(0, declRefExpr(to(varDecl()))),
428 hasArgument(1, hasType(pointsTo(
429 recordDecl(hasName("T"))))),
430 hasArgument(2, integerLiteral(equals(3))),
431 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000432}
433
Manuel Klimek04616e42012-07-06 05:48:52 +0000434TEST(DeclarationMatcher, MatchAnyOf) {
435 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000436 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000437 EXPECT_TRUE(
438 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
439 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
440 EXPECT_TRUE(
441 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
442 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
443
Daniel Jasper84c763e2012-07-15 19:57:12 +0000444 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000445 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000446 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
447 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
448
Manuel Klimek04616e42012-07-06 05:48:52 +0000449 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000450 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
451 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000452 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
453 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
454 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
455 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
456 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
457 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
458}
459
460TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000461 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000462 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
463 EXPECT_TRUE(matches("class X {};", HasClassX));
464
465 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000466 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000467 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
468 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
469 EXPECT_TRUE(
470 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
471}
472
473TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
474 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000475 recordDecl(
476 has(recordDecl(
477 has(recordDecl(hasName("X"))),
478 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000479 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000480 has(recordDecl(
481 has(recordDecl(hasName("A"))),
482 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000483 hasName("C"))),
484 hasName("F"));
485
486 EXPECT_TRUE(matches(
487 "class F {"
488 " class Z {"
489 " class X {};"
490 " class Y {};"
491 " };"
492 " class C {"
493 " class A {};"
494 " class B {};"
495 " };"
496 "};", Recursive));
497
498 EXPECT_TRUE(matches(
499 "class F {"
500 " class Z {"
501 " class A {};"
502 " class X {};"
503 " class Y {};"
504 " };"
505 " class C {"
506 " class X {};"
507 " class A {};"
508 " class B {};"
509 " };"
510 "};", Recursive));
511
512 EXPECT_TRUE(matches(
513 "class O1 {"
514 " class O2 {"
515 " class F {"
516 " class Z {"
517 " class A {};"
518 " class X {};"
519 " class Y {};"
520 " };"
521 " class C {"
522 " class X {};"
523 " class A {};"
524 " class B {};"
525 " };"
526 " };"
527 " };"
528 "};", Recursive));
529}
530
531TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
532 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000533 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000534 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000535 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000536 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000537 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000538 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000539 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000540 hasName("Y"))),
541 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000542 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000543 anyOf(
544 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000545 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000546 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000547 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000548 hasName("B")))))),
549 hasName("F")));
550
551 EXPECT_TRUE(matches("class F {};", Recursive));
552 EXPECT_TRUE(matches("class Z {};", Recursive));
553 EXPECT_TRUE(matches("class C {};", Recursive));
554 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
555 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
556 EXPECT_TRUE(
557 matches("class O1 { class O2 {"
558 " class M { class N { class B {}; }; }; "
559 "}; };", Recursive));
560}
561
562TEST(DeclarationMatcher, MatchNot) {
563 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000564 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000565 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000566 unless(hasName("X")));
567 EXPECT_TRUE(notMatches("", NotClassX));
568 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
569 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
570 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
571 EXPECT_TRUE(
572 notMatches("class Y {}; class Z {}; class X : public Y {};",
573 NotClassX));
574
575 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000576 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000577 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000578 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000579 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000580 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000581 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
582 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
583 ClassXHasNotClassY));
584}
585
586TEST(DeclarationMatcher, HasDescendant) {
587 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000588 recordDecl(
589 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000590 hasName("Z"));
591 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
592 EXPECT_TRUE(
593 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
594 EXPECT_TRUE(
595 matches("class Z { class A { class Y { class X {}; }; }; };",
596 ZDescendantClassX));
597 EXPECT_TRUE(
598 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
599 ZDescendantClassX));
600 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
601
602 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000603 recordDecl(
604 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000605 hasName("X"))),
606 hasName("Z"));
607 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
608 ZDescendantClassXHasClassY));
609 EXPECT_TRUE(
610 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
611 ZDescendantClassXHasClassY));
612 EXPECT_TRUE(notMatches(
613 "class Z {"
614 " class A {"
615 " class B {"
616 " class X {"
617 " class C {"
618 " class Y {};"
619 " };"
620 " };"
621 " }; "
622 " };"
623 "};", ZDescendantClassXHasClassY));
624
625 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000626 recordDecl(
627 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
628 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000629 hasName("Z"));
630 EXPECT_TRUE(
631 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
632 ZDescendantClassXDescendantClassY));
633 EXPECT_TRUE(matches(
634 "class Z {"
635 " class A {"
636 " class X {"
637 " class B {"
638 " class Y {};"
639 " };"
640 " class Y {};"
641 " };"
642 " };"
643 "};", ZDescendantClassXDescendantClassY));
644}
645
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000646TEST(DeclarationMatcher, HasDescendantMemoization) {
647 DeclarationMatcher CannotMemoize =
648 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
649 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
650}
651
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000652TEST(DeclarationMatcher, HasAttr) {
653 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
654 decl(hasAttr(clang::attr::WarnUnused))));
655 EXPECT_FALSE(matches("struct X {};",
656 decl(hasAttr(clang::attr::WarnUnused))));
657}
658
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000659TEST(DeclarationMatcher, MatchCudaDecl) {
660 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
661 "void g() { f<<<1, 2>>>(); }",
662 CUDAKernelCallExpr()));
663 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000664 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000665 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000666 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000667 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000668 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000669}
670
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000671// Implements a run method that returns whether BoundNodes contains a
672// Decl bound to Id that can be dynamically cast to T.
673// Optionally checks that the check succeeded a specific number of times.
674template <typename T>
675class VerifyIdIsBoundTo : public BoundNodesCallback {
676public:
677 // Create an object that checks that a node of type \c T was bound to \c Id.
678 // Does not check for a certain number of matches.
679 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
680 : Id(Id), ExpectedCount(-1), Count(0) {}
681
682 // Create an object that checks that a node of type \c T was bound to \c Id.
683 // Checks that there were exactly \c ExpectedCount matches.
684 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
685 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
686
687 // Create an object that checks that a node of type \c T was bound to \c Id.
688 // Checks that there was exactly one match with the name \c ExpectedName.
689 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000690 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
691 int ExpectedCount = 1)
692 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
693 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000694
Craig Toppera798a9d2014-03-02 09:32:10 +0000695 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000696 if (ExpectedCount != -1)
697 EXPECT_EQ(ExpectedCount, Count);
698 if (!ExpectedName.empty())
699 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000700 Count = 0;
701 Name.clear();
702 }
703
704 ~VerifyIdIsBoundTo() {
705 EXPECT_EQ(0, Count);
706 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000707 }
708
709 virtual bool run(const BoundNodes *Nodes) {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000710 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000711 if (Nodes->getNodeAs<T>(Id)) {
712 ++Count;
713 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
714 Name = Named->getNameAsString();
715 } else if (const NestedNameSpecifier *NNS =
716 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
717 llvm::raw_string_ostream OS(Name);
718 NNS->print(OS, PrintingPolicy(LangOptions()));
719 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000720 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
721 EXPECT_NE(M.end(), I);
722 if (I != M.end())
723 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000724 return true;
725 }
Craig Topper416fa342014-06-08 08:38:12 +0000726 EXPECT_TRUE(M.count(Id) == 0 ||
727 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000728 return false;
729 }
730
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000731 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
732 return run(Nodes);
733 }
734
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000735private:
736 const std::string Id;
737 const int ExpectedCount;
738 int Count;
739 const std::string ExpectedName;
740 std::string Name;
741};
742
743TEST(HasDescendant, MatchesDescendantTypes) {
744 EXPECT_TRUE(matches("void f() { int i = 3; }",
745 decl(hasDescendant(loc(builtinType())))));
746 EXPECT_TRUE(matches("void f() { int i = 3; }",
747 stmt(hasDescendant(builtinType()))));
748
749 EXPECT_TRUE(matches("void f() { int i = 3; }",
750 stmt(hasDescendant(loc(builtinType())))));
751 EXPECT_TRUE(matches("void f() { int i = 3; }",
752 stmt(hasDescendant(qualType(builtinType())))));
753
754 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
755 stmt(hasDescendant(isInteger()))));
756
757 EXPECT_TRUE(matchAndVerifyResultTrue(
758 "void f() { int a; float c; int d; int e; }",
759 functionDecl(forEachDescendant(
760 varDecl(hasDescendant(isInteger())).bind("x"))),
761 new VerifyIdIsBoundTo<Decl>("x", 3)));
762}
763
764TEST(HasDescendant, MatchesDescendantsOfTypes) {
765 EXPECT_TRUE(matches("void f() { int*** i; }",
766 qualType(hasDescendant(builtinType()))));
767 EXPECT_TRUE(matches("void f() { int*** i; }",
768 qualType(hasDescendant(
769 pointerType(pointee(builtinType()))))));
770 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000771 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000772
773 EXPECT_TRUE(matchAndVerifyResultTrue(
774 "void f() { int*** i; }",
775 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
776 new VerifyIdIsBoundTo<Type>("x", 2)));
777}
778
779TEST(Has, MatchesChildrenOfTypes) {
780 EXPECT_TRUE(matches("int i;",
781 varDecl(hasName("i"), has(isInteger()))));
782 EXPECT_TRUE(notMatches("int** i;",
783 varDecl(hasName("i"), has(isInteger()))));
784 EXPECT_TRUE(matchAndVerifyResultTrue(
785 "int (*f)(float, int);",
786 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
787 new VerifyIdIsBoundTo<QualType>("x", 2)));
788}
789
790TEST(Has, MatchesChildTypes) {
791 EXPECT_TRUE(matches(
792 "int* i;",
793 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
794 EXPECT_TRUE(notMatches(
795 "int* i;",
796 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
797}
798
Daniel Jasper1dad1832012-07-10 20:20:19 +0000799TEST(Enum, DoesNotMatchClasses) {
800 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
801}
802
803TEST(Enum, MatchesEnums) {
804 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
805}
806
807TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000808 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000809 EXPECT_TRUE(matches("enum X{ A };", Matcher));
810 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
811 EXPECT_TRUE(notMatches("enum X {};", Matcher));
812}
813
Manuel Klimek04616e42012-07-06 05:48:52 +0000814TEST(StatementMatcher, Has) {
815 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000816 expr(hasType(pointsTo(recordDecl(hasName("X")))),
817 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000818
819 EXPECT_TRUE(matches(
820 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
821 EXPECT_TRUE(notMatches(
822 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
823}
824
825TEST(StatementMatcher, HasDescendant) {
826 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000827 expr(hasType(pointsTo(recordDecl(hasName("X")))),
828 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000829
830 EXPECT_TRUE(matches(
831 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
832 HasDescendantVariableI));
833 EXPECT_TRUE(notMatches(
834 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
835 HasDescendantVariableI));
836}
837
838TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000839 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000840
841 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
842 EXPECT_TRUE(notMatches("class A {};", TypeA));
843
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000844 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000845
846 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
847 TypeDerivedFromA));
848 EXPECT_TRUE(notMatches("class A {};", TypeA));
849
850 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000851 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000852
853 EXPECT_TRUE(
854 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
855}
856
Manuel Klimek04616e42012-07-06 05:48:52 +0000857TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000858 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000859
860 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000861 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000862
863 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000864 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000865
866 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000867 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000868
869 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
870 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000871 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000872
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000873 StatementMatcher MethodX =
874 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000875
876 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
877 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000878 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000879}
880
881TEST(Matcher, BindTheSameNameInAlternatives) {
882 StatementMatcher matcher = anyOf(
883 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000884 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000885 hasRHS(integerLiteral(equals(0)))),
886 binaryOperator(hasOperatorName("+"),
887 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000888 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000889
890 EXPECT_TRUE(matchAndVerifyResultTrue(
891 // The first branch of the matcher binds x to 0 but then fails.
892 // The second branch binds x to f() and succeeds.
893 "int f() { return 0 + f(); }",
894 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000895 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000896}
897
Manuel Klimekfdf98762012-08-30 19:41:06 +0000898TEST(Matcher, BindsIDForMemoizedResults) {
899 // Using the same matcher in two match expressions will make memoization
900 // kick in.
901 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
902 EXPECT_TRUE(matchAndVerifyResultTrue(
903 "class A { class B { class X {}; }; };",
904 DeclarationMatcher(anyOf(
905 recordDecl(hasName("A"), hasDescendant(ClassX)),
906 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000907 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000908}
909
Daniel Jasper856194d02012-12-03 15:43:25 +0000910TEST(HasDeclaration, HasDeclarationOfEnumType) {
911 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
912 expr(hasType(pointsTo(
913 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
914}
915
Edwin Vaneed936452013-02-25 14:32:42 +0000916TEST(HasDeclaration, HasGetDeclTraitTest) {
917 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
918 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
919 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
920}
921
Edwin Vane2c197e02013-02-19 17:14:34 +0000922TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
923 EXPECT_TRUE(matches("typedef int X; X a;",
924 varDecl(hasName("a"),
925 hasType(typedefType(hasDeclaration(decl()))))));
926
927 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
928}
929
Edwin Vanef901b712013-02-25 14:49:29 +0000930TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
931 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
932 varDecl(hasType(templateSpecializationType(
933 hasDeclaration(namedDecl(hasName("A"))))))));
934}
935
Manuel Klimek04616e42012-07-06 05:48:52 +0000936TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000937 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000938 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000939 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000940 EXPECT_TRUE(
941 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000942 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000943 EXPECT_TRUE(
944 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000945 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000946}
947
948TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000949 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000950 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000951 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000952 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000953 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000954 EXPECT_TRUE(
955 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000956 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000957}
958
959TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000960 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000961 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000962 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000963 EXPECT_TRUE(
964 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000965 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000966}
967
968TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000969 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000970 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000971 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000972 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000973 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000974}
975
Manuel Klimekc16c6522013-06-20 13:08:29 +0000976TEST(HasTypeLoc, MatchesDeclaratorDecls) {
977 EXPECT_TRUE(matches("int x;",
978 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
979
980 // Make sure we don't crash on implicit constructors.
981 EXPECT_TRUE(notMatches("class X {}; X x;",
982 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
983}
984
Manuel Klimek04616e42012-07-06 05:48:52 +0000985TEST(Matcher, Call) {
986 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +0000987 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000988 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000989
990 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
991 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
992
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000993 StatementMatcher MethodOnY =
994 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000995
996 EXPECT_TRUE(
997 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
998 MethodOnY));
999 EXPECT_TRUE(
1000 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1001 MethodOnY));
1002 EXPECT_TRUE(
1003 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1004 MethodOnY));
1005 EXPECT_TRUE(
1006 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1007 MethodOnY));
1008 EXPECT_TRUE(
1009 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1010 MethodOnY));
1011
1012 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001013 memberCallExpr(on(hasType(pointsTo(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 MethodOnYPointer));
1018 EXPECT_TRUE(
1019 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1020 MethodOnYPointer));
1021 EXPECT_TRUE(
1022 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1023 MethodOnYPointer));
1024 EXPECT_TRUE(
1025 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1026 MethodOnYPointer));
1027 EXPECT_TRUE(
1028 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1029 MethodOnYPointer));
1030}
1031
Daniel Jasper5901e472012-10-01 13:40:41 +00001032TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001033 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001034 lambdaExpr()));
1035}
1036
1037TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001038 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1039 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001040 forRangeStmt()));
1041 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1042 forRangeStmt()));
1043}
1044
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001045TEST(Matcher, SubstNonTypeTemplateParm) {
1046 EXPECT_FALSE(matches("template<int N>\n"
1047 "struct A { static const int n = 0; };\n"
1048 "struct B : public A<42> {};",
1049 substNonTypeTemplateParmExpr()));
1050 EXPECT_TRUE(matches("template<int N>\n"
1051 "struct A { static const int n = N; };\n"
1052 "struct B : public A<42> {};",
1053 substNonTypeTemplateParmExpr()));
1054}
1055
Daniel Jasper5901e472012-10-01 13:40:41 +00001056TEST(Matcher, UserDefinedLiteral) {
1057 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1058 " return i + 1;"
1059 "}"
1060 "char c = 'a'_inc;",
1061 userDefinedLiteral()));
1062}
1063
Daniel Jasper87c3d362012-09-20 14:12:57 +00001064TEST(Matcher, FlowControl) {
1065 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1066 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1067 continueStmt()));
1068 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1069 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1070 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1071}
1072
Daniel Jasper1dad1832012-07-10 20:20:19 +00001073TEST(HasType, MatchesAsString) {
1074 EXPECT_TRUE(
1075 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001076 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001077 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001078 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001079 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001080 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001081 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001082 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001083}
1084
Manuel Klimek04616e42012-07-06 05:48:52 +00001085TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001086 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001087 // Unary operator
1088 EXPECT_TRUE(matches("class Y { }; "
1089 "bool operator!(Y x) { return false; }; "
1090 "Y y; bool c = !y;", OpCall));
1091 // No match -- special operators like "new", "delete"
1092 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1093 // we need to figure out include paths in the test.
1094 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1095 // "class Y { }; "
1096 // "void *operator new(size_t size) { return 0; } "
1097 // "Y *y = new Y;", OpCall));
1098 EXPECT_TRUE(notMatches("class Y { }; "
1099 "void operator delete(void *p) { } "
1100 "void a() {Y *y = new Y; delete y;}", OpCall));
1101 // Binary operator
1102 EXPECT_TRUE(matches("class Y { }; "
1103 "bool operator&&(Y x, Y y) { return true; }; "
1104 "Y a; Y b; bool c = a && b;",
1105 OpCall));
1106 // No match -- normal operator, not an overloaded one.
1107 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1108 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1109}
1110
1111TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1112 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001113 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001114 EXPECT_TRUE(matches("class Y { }; "
1115 "bool operator&&(Y x, Y y) { return true; }; "
1116 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1117 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001118 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001119 EXPECT_TRUE(notMatches("class Y { }; "
1120 "bool operator&&(Y x, Y y) { return true; }; "
1121 "Y a; Y b; bool c = a && b;",
1122 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001123 StatementMatcher OpStarCall =
1124 operatorCallExpr(hasOverloadedOperatorName("*"));
1125 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1126 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001127 DeclarationMatcher ClassWithOpStar =
1128 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1129 EXPECT_TRUE(matches("class Y { int operator*(); };",
1130 ClassWithOpStar));
1131 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1132 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001133 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1134 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1135 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001136}
1137
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001138TEST(Matcher, NestedOverloadedOperatorCalls) {
1139 EXPECT_TRUE(matchAndVerifyResultTrue(
1140 "class Y { }; "
1141 "Y& operator&&(Y& x, Y& y) { return x; }; "
1142 "Y a; Y b; Y c; Y d = a && b && c;",
1143 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1144 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1145 EXPECT_TRUE(matches(
1146 "class Y { }; "
1147 "Y& operator&&(Y& x, Y& y) { return x; }; "
1148 "Y a; Y b; Y c; Y d = a && b && c;",
1149 operatorCallExpr(hasParent(operatorCallExpr()))));
1150 EXPECT_TRUE(matches(
1151 "class Y { }; "
1152 "Y& operator&&(Y& x, Y& y) { return x; }; "
1153 "Y a; Y b; Y c; Y d = a && b && c;",
1154 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1155}
1156
Manuel Klimek04616e42012-07-06 05:48:52 +00001157TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001158 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001159 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001160
1161 EXPECT_TRUE(
1162 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1163 MethodOnY));
1164 EXPECT_TRUE(
1165 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1166 MethodOnY));
1167 EXPECT_TRUE(
1168 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1169 MethodOnY));
1170 EXPECT_TRUE(
1171 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1172 MethodOnY));
1173 EXPECT_TRUE(
1174 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1175 MethodOnY));
1176
1177 EXPECT_TRUE(matches(
1178 "class Y {"
1179 " public: virtual void x();"
1180 "};"
1181 "class X : public Y {"
1182 " public: virtual void x();"
1183 "};"
1184 "void z() { X *x; x->Y::x(); }", MethodOnY));
1185}
1186
1187TEST(Matcher, VariableUsage) {
1188 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001189 declRefExpr(to(
1190 varDecl(hasInitializer(
1191 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001192
1193 EXPECT_TRUE(matches(
1194 "class Y {"
1195 " public:"
1196 " bool x() const;"
1197 "};"
1198 "void z(const Y &y) {"
1199 " bool b = y.x();"
1200 " if (b) {}"
1201 "}", Reference));
1202
1203 EXPECT_TRUE(notMatches(
1204 "class Y {"
1205 " public:"
1206 " bool x() const;"
1207 "};"
1208 "void z(const Y &y) {"
1209 " bool b = y.x();"
1210 "}", Reference));
1211}
1212
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001213TEST(Matcher, VarDecl_Storage) {
1214 auto M = varDecl(hasName("X"), hasLocalStorage());
1215 EXPECT_TRUE(matches("void f() { int X; }", M));
1216 EXPECT_TRUE(notMatches("int X;", M));
1217 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1218
1219 M = varDecl(hasName("X"), hasGlobalStorage());
1220 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1221 EXPECT_TRUE(matches("int X;", M));
1222 EXPECT_TRUE(matches("void f() { static int X; }", M));
1223}
1224
Manuel Klimek61379422012-12-04 14:42:08 +00001225TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001226 EXPECT_TRUE(matches(
1227 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001228 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001229}
1230
Manuel Klimek04616e42012-07-06 05:48:52 +00001231TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001232 StatementMatcher CallOnVariableY =
1233 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001234
1235 EXPECT_TRUE(matches(
1236 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1237 EXPECT_TRUE(matches(
1238 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1239 EXPECT_TRUE(matches(
1240 "class Y { public: void x(); };"
1241 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1242 EXPECT_TRUE(matches(
1243 "class Y { public: void x(); };"
1244 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1245 EXPECT_TRUE(notMatches(
1246 "class Y { public: void x(); };"
1247 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1248 CallOnVariableY));
1249}
1250
Daniel Jasper1dad1832012-07-10 20:20:19 +00001251TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1252 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1253 unaryExprOrTypeTraitExpr()));
1254 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1255 alignOfExpr(anything())));
1256 // FIXME: Uncomment once alignof is enabled.
1257 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1258 // unaryExprOrTypeTraitExpr()));
1259 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1260 // sizeOfExpr()));
1261}
1262
1263TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1264 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1265 hasArgumentOfType(asString("int")))));
1266 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1267 hasArgumentOfType(asString("float")))));
1268 EXPECT_TRUE(matches(
1269 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001270 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001271 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001272 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001273}
1274
Manuel Klimek04616e42012-07-06 05:48:52 +00001275TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001276 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001277}
1278
1279TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001280 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001281}
1282
1283TEST(MemberExpression, MatchesVariable) {
1284 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001285 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001286 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001287 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001288 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001289 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001290}
1291
1292TEST(MemberExpression, MatchesStaticVariable) {
1293 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001294 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001295 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001296 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001297 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001298 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001299}
1300
Daniel Jasper4e566c42012-07-12 08:50:38 +00001301TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001302 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1303 EXPECT_TRUE(matches(
1304 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1305 callExpr(hasArgument(0, declRefExpr(
1306 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001307}
1308
1309TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001310 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001311 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001312 callExpr(hasArgument(0, declRefExpr(
1313 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001314}
1315
Manuel Klimek04616e42012-07-06 05:48:52 +00001316TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1317 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001318 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001319 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001320 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001321 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001322 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001323}
1324
1325TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1326 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001327 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001328 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001329 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001330 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001331 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001332}
1333
1334TEST(IsArrow, MatchesMemberCallsViaArrow) {
1335 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001336 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001337 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001338 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001339 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001340 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001341}
1342
1343TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001344 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001345
1346 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1347 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1348}
1349
1350TEST(Callee, MatchesMemberExpressions) {
1351 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001352 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001353 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001354 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001355}
1356
1357TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001358 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001359
1360 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1361 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1362
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001363 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1364 llvm::Triple::Win32) {
1365 // FIXME: Make this work for MSVC.
1366 // Dependent contexts, but a non-dependent call.
1367 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1368 CallFunctionF));
1369 EXPECT_TRUE(
1370 matches("void f(); template <int N> struct S { void g() { f(); } };",
1371 CallFunctionF));
1372 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001373
1374 // Depedent calls don't match.
1375 EXPECT_TRUE(
1376 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1377 CallFunctionF));
1378 EXPECT_TRUE(
1379 notMatches("void f(int);"
1380 "template <typename T> struct S { void g(T t) { f(t); } };",
1381 CallFunctionF));
1382}
1383
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001384TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1385 EXPECT_TRUE(
1386 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001387 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001388}
1389
1390TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1391 EXPECT_TRUE(
1392 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001393 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001394}
1395
1396TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1397 EXPECT_TRUE(
1398 notMatches("void g(); template <typename T> void f(T t) {}"
1399 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001400 functionTemplateDecl(hasName("f"),
1401 hasDescendant(declRefExpr(to(
1402 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001403}
1404
Manuel Klimek04616e42012-07-06 05:48:52 +00001405TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001406 StatementMatcher CallArgumentY = callExpr(
1407 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001408
1409 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1410 EXPECT_TRUE(
1411 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1412 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1413
Daniel Jasper848cbe12012-09-18 13:09:13 +00001414 StatementMatcher WrongIndex = callExpr(
1415 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001416 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1417}
1418
1419TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001420 StatementMatcher CallArgumentY = callExpr(
1421 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001422 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1423 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1424 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1425}
1426
1427TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001428 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001429
1430 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1431 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1432 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1433}
1434
Daniel Jasper9f501292012-12-04 11:54:27 +00001435TEST(Matcher, ParameterCount) {
1436 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1437 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1438 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1439 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1440 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1441}
1442
Manuel Klimek04616e42012-07-06 05:48:52 +00001443TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001444 DeclarationMatcher ReferenceClassX = varDecl(
1445 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001446 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1447 ReferenceClassX));
1448 EXPECT_TRUE(
1449 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001450 // The match here is on the implicit copy constructor code for
1451 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001452 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001453 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1454 EXPECT_TRUE(
1455 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001456 EXPECT_TRUE(
1457 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1458}
1459
Edwin Vane0a4836e2013-03-06 17:02:57 +00001460TEST(QualType, hasCanonicalType) {
1461 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1462 "int a;"
1463 "int_ref b = a;",
1464 varDecl(hasType(qualType(referenceType())))));
1465 EXPECT_TRUE(
1466 matches("typedef int &int_ref;"
1467 "int a;"
1468 "int_ref b = a;",
1469 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1470}
1471
Edwin Vane119d3df2013-04-02 18:15:55 +00001472TEST(QualType, hasLocalQualifiers) {
1473 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1474 varDecl(hasType(hasLocalQualifiers()))));
1475 EXPECT_TRUE(matches("int *const j = nullptr;",
1476 varDecl(hasType(hasLocalQualifiers()))));
1477 EXPECT_TRUE(matches("int *volatile k;",
1478 varDecl(hasType(hasLocalQualifiers()))));
1479 EXPECT_TRUE(notMatches("int m;",
1480 varDecl(hasType(hasLocalQualifiers()))));
1481}
1482
Manuel Klimek04616e42012-07-06 05:48:52 +00001483TEST(HasParameter, CallsInnerMatcher) {
1484 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001485 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001486 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001487 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001488}
1489
1490TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1491 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001492 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001493}
1494
1495TEST(HasType, MatchesParameterVariableTypesStrictly) {
1496 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001497 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001498 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001499 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001500 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001501 methodDecl(hasParameter(0,
1502 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001503 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001504 methodDecl(hasParameter(0,
1505 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001506}
1507
1508TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1509 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001510 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001511 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001512 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001513}
1514
Daniel Jasper1dad1832012-07-10 20:20:19 +00001515TEST(Returns, MatchesReturnTypes) {
1516 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001517 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001518 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001519 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001520 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001521 functionDecl(returns(hasDeclaration(
1522 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001523}
1524
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001525TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001526 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1527 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1528 functionDecl(isExternC())));
1529 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001530}
1531
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001532TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1533 EXPECT_TRUE(
1534 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1535 EXPECT_TRUE(matches("void Func() = delete;",
1536 functionDecl(hasName("Func"), isDeleted())));
1537}
1538
Manuel Klimek04616e42012-07-06 05:48:52 +00001539TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1540 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001541 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001542}
1543
1544TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1545 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001546 methodDecl(hasAnyParameter(hasType(pointsTo(
1547 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001548}
1549
Alp Toker8db6e7a2014-01-05 06:38:57 +00001550TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001551 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001552 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001553 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001554 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001555}
1556
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001557TEST(Matcher, MatchesClassTemplateSpecialization) {
1558 EXPECT_TRUE(matches("template<typename T> struct A {};"
1559 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001560 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001561 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001562 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001563 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001564 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001565}
1566
Manuel Klimekc16c6522013-06-20 13:08:29 +00001567TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1568 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1569 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1570}
1571
1572TEST(ParmVarDecl, MatchesParmVars) {
1573 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1574 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1575}
1576
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001577TEST(Matcher, MatchesTypeTemplateArgument) {
1578 EXPECT_TRUE(matches(
1579 "template<typename T> struct B {};"
1580 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001581 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001582 asString("int"))))));
1583}
1584
1585TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1586 EXPECT_TRUE(matches(
1587 "struct B { int next; };"
1588 "template<int(B::*next_ptr)> struct A {};"
1589 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001590 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1591 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001592
1593 EXPECT_TRUE(notMatches(
1594 "template <typename T> struct A {};"
1595 "A<int> a;",
1596 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1597 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001598
1599 EXPECT_TRUE(matches(
1600 "struct B { int next; };"
1601 "template<int(B::*next_ptr)> struct A {};"
1602 "A<&B::next> a;",
1603 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1604 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1605
1606 EXPECT_TRUE(notMatches(
1607 "template <typename T> struct A {};"
1608 "A<int> a;",
1609 templateSpecializationType(hasAnyTemplateArgument(
1610 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001611}
1612
1613TEST(Matcher, MatchesSpecificArgument) {
1614 EXPECT_TRUE(matches(
1615 "template<typename T, typename U> class A {};"
1616 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001617 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001618 1, refersToType(asString("int"))))));
1619 EXPECT_TRUE(notMatches(
1620 "template<typename T, typename U> class A {};"
1621 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001622 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001623 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001624
1625 EXPECT_TRUE(matches(
1626 "template<typename T, typename U> class A {};"
1627 "A<bool, int> a;",
1628 templateSpecializationType(hasTemplateArgument(
1629 1, refersToType(asString("int"))))));
1630 EXPECT_TRUE(notMatches(
1631 "template<typename T, typename U> class A {};"
1632 "A<int, bool> a;",
1633 templateSpecializationType(hasTemplateArgument(
1634 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001635}
1636
Daniel Jasper639522c2013-02-25 12:02:08 +00001637TEST(Matcher, MatchesAccessSpecDecls) {
1638 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1639 EXPECT_TRUE(
1640 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1641 EXPECT_TRUE(
1642 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1643 EXPECT_TRUE(
1644 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1645
1646 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1647}
1648
Edwin Vane37ee1d72013-04-09 20:46:36 +00001649TEST(Matcher, MatchesVirtualMethod) {
1650 EXPECT_TRUE(matches("class X { virtual int f(); };",
1651 methodDecl(isVirtual(), hasName("::X::f"))));
1652 EXPECT_TRUE(notMatches("class X { int f(); };",
1653 methodDecl(isVirtual())));
1654}
1655
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001656TEST(Matcher, MatchesPureMethod) {
1657 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1658 methodDecl(isPure(), hasName("::X::f"))));
1659 EXPECT_TRUE(notMatches("class X { int f(); };",
1660 methodDecl(isPure())));
1661}
1662
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001663TEST(Matcher, MatchesConstMethod) {
1664 EXPECT_TRUE(matches("struct A { void foo() const; };",
1665 methodDecl(isConst())));
1666 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1667 methodDecl(isConst())));
1668}
1669
Edwin Vane37ee1d72013-04-09 20:46:36 +00001670TEST(Matcher, MatchesOverridingMethod) {
1671 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1672 "class Y : public X { int f(); };",
1673 methodDecl(isOverride(), hasName("::Y::f"))));
1674 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1675 "class Y : public X { int f(); };",
1676 methodDecl(isOverride(), hasName("::X::f"))));
1677 EXPECT_TRUE(notMatches("class X { int f(); }; "
1678 "class Y : public X { int f(); };",
1679 methodDecl(isOverride())));
1680 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1681 methodDecl(isOverride())));
1682}
1683
Manuel Klimek04616e42012-07-06 05:48:52 +00001684TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001685 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001686
1687 EXPECT_TRUE(
1688 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1689 EXPECT_TRUE(
1690 matches("class X { public: X(); }; void x() { X x = X(); }",
1691 Constructor));
1692 EXPECT_TRUE(
1693 matches("class X { public: X(int); }; void x() { X x = 0; }",
1694 Constructor));
1695 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1696}
1697
1698TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001699 StatementMatcher Constructor = constructExpr(
1700 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001701
1702 EXPECT_TRUE(
1703 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1704 Constructor));
1705 EXPECT_TRUE(
1706 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1707 Constructor));
1708 EXPECT_TRUE(
1709 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1710 Constructor));
1711 EXPECT_TRUE(
1712 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1713 Constructor));
1714
Daniel Jasper848cbe12012-09-18 13:09:13 +00001715 StatementMatcher WrongIndex = constructExpr(
1716 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001717 EXPECT_TRUE(
1718 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1719 WrongIndex));
1720}
1721
1722TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001723 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001724
1725 EXPECT_TRUE(
1726 matches("class X { public: X(int); }; void x() { X x(0); }",
1727 Constructor1Arg));
1728 EXPECT_TRUE(
1729 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1730 Constructor1Arg));
1731 EXPECT_TRUE(
1732 matches("class X { public: X(int); }; void x() { X x = 0; }",
1733 Constructor1Arg));
1734 EXPECT_TRUE(
1735 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1736 Constructor1Arg));
1737}
1738
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001739TEST(Matcher, ConstructorListInitialization) {
1740 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1741
1742 EXPECT_TRUE(
1743 matches("class X { public: X(int); }; void x() { X x{0}; }",
1744 ConstructorListInit));
1745 EXPECT_FALSE(
1746 matches("class X { public: X(int); }; void x() { X x(0); }",
1747 ConstructorListInit));
1748}
1749
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001750TEST(Matcher,ThisExpr) {
1751 EXPECT_TRUE(
1752 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1753 EXPECT_TRUE(
1754 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1755}
1756
Manuel Klimek04616e42012-07-06 05:48:52 +00001757TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001758 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001759
1760 std::string ClassString = "class string { public: string(); ~string(); }; ";
1761
1762 EXPECT_TRUE(
1763 matches(ClassString +
1764 "string GetStringByValue();"
1765 "void FunctionTakesString(string s);"
1766 "void run() { FunctionTakesString(GetStringByValue()); }",
1767 TempExpression));
1768
1769 EXPECT_TRUE(
1770 notMatches(ClassString +
1771 "string* GetStringPointer(); "
1772 "void FunctionTakesStringPtr(string* s);"
1773 "void run() {"
1774 " string* s = GetStringPointer();"
1775 " FunctionTakesStringPtr(GetStringPointer());"
1776 " FunctionTakesStringPtr(s);"
1777 "}",
1778 TempExpression));
1779
1780 EXPECT_TRUE(
1781 notMatches("class no_dtor {};"
1782 "no_dtor GetObjByValue();"
1783 "void ConsumeObj(no_dtor param);"
1784 "void run() { ConsumeObj(GetObjByValue()); }",
1785 TempExpression));
1786}
1787
Sam Panzer68a35af2012-08-24 22:04:44 +00001788TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1789 std::string ClassString =
1790 "class string { public: string(); int length(); }; ";
1791
1792 EXPECT_TRUE(
1793 matches(ClassString +
1794 "string GetStringByValue();"
1795 "void FunctionTakesString(string s);"
1796 "void run() { FunctionTakesString(GetStringByValue()); }",
1797 materializeTemporaryExpr()));
1798
1799 EXPECT_TRUE(
1800 notMatches(ClassString +
1801 "string* GetStringPointer(); "
1802 "void FunctionTakesStringPtr(string* s);"
1803 "void run() {"
1804 " string* s = GetStringPointer();"
1805 " FunctionTakesStringPtr(GetStringPointer());"
1806 " FunctionTakesStringPtr(s);"
1807 "}",
1808 materializeTemporaryExpr()));
1809
1810 EXPECT_TRUE(
1811 notMatches(ClassString +
1812 "string GetStringByValue();"
1813 "void run() { int k = GetStringByValue().length(); }",
1814 materializeTemporaryExpr()));
1815
1816 EXPECT_TRUE(
1817 notMatches(ClassString +
1818 "string GetStringByValue();"
1819 "void run() { GetStringByValue(); }",
1820 materializeTemporaryExpr()));
1821}
1822
Manuel Klimek04616e42012-07-06 05:48:52 +00001823TEST(ConstructorDeclaration, SimpleCase) {
1824 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001825 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001826 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001827 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001828}
1829
1830TEST(ConstructorDeclaration, IsImplicit) {
1831 // This one doesn't match because the constructor is not added by the
1832 // compiler (it is not needed).
1833 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001834 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001835 // The compiler added the implicit default constructor.
1836 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001837 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001838 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001839 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001840 // The compiler added an implicit assignment operator.
1841 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1842 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001843}
1844
Daniel Jasper1dad1832012-07-10 20:20:19 +00001845TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1846 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001847 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001848}
1849
1850TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001851 EXPECT_TRUE(notMatches("class Foo {};",
1852 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001853}
1854
Manuel Klimek04616e42012-07-06 05:48:52 +00001855TEST(HasAnyConstructorInitializer, SimpleCase) {
1856 EXPECT_TRUE(notMatches(
1857 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001858 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001859 EXPECT_TRUE(matches(
1860 "class Foo {"
1861 " Foo() : foo_() { }"
1862 " int foo_;"
1863 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001864 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001865}
1866
1867TEST(HasAnyConstructorInitializer, ForField) {
1868 static const char Code[] =
1869 "class Baz { };"
1870 "class Foo {"
1871 " Foo() : foo_() { }"
1872 " Baz foo_;"
1873 " Baz bar_;"
1874 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001875 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1876 forField(hasType(recordDecl(hasName("Baz"))))))));
1877 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001878 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001879 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1880 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001881}
1882
1883TEST(HasAnyConstructorInitializer, WithInitializer) {
1884 static const char Code[] =
1885 "class Foo {"
1886 " Foo() : foo_(0) { }"
1887 " int foo_;"
1888 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001889 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001890 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001891 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001892 withInitializer(integerLiteral(equals(1)))))));
1893}
1894
1895TEST(HasAnyConstructorInitializer, IsWritten) {
1896 static const char Code[] =
1897 "struct Bar { Bar(){} };"
1898 "class Foo {"
1899 " Foo() : foo_() { }"
1900 " Bar foo_;"
1901 " Bar bar_;"
1902 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001903 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001904 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001905 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001906 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001907 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001908 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1909}
1910
1911TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001912 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001913
1914 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
1915 EXPECT_TRUE(
1916 matches("class X { public: X(); }; void x() { new X(); }", New));
1917 EXPECT_TRUE(
1918 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1919 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
1920}
1921
1922TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001923 StatementMatcher New = constructExpr(
1924 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001925
1926 EXPECT_TRUE(
1927 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1928 New));
1929 EXPECT_TRUE(
1930 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1931 New));
1932 EXPECT_TRUE(
1933 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
1934 New));
1935
Daniel Jasper848cbe12012-09-18 13:09:13 +00001936 StatementMatcher WrongIndex = constructExpr(
1937 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001938 EXPECT_TRUE(
1939 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
1940 WrongIndex));
1941}
1942
1943TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001944 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001945
1946 EXPECT_TRUE(
1947 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1948 EXPECT_TRUE(
1949 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
1950 New));
1951}
1952
Daniel Jasper1dad1832012-07-10 20:20:19 +00001953TEST(Matcher, DeleteExpression) {
1954 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001955 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001956}
1957
Manuel Klimek04616e42012-07-06 05:48:52 +00001958TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001959 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001960
1961 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
1962 EXPECT_TRUE(
1963 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
1964 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
1965}
1966
1967TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001968 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001969 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
1970 // wide string
1971 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
1972 // with escaped characters
1973 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
1974 // no matching -- though the data type is the same, there is no string literal
1975 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
1976}
1977
1978TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001979 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001980 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
1981 // wide character
1982 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
1983 // wide character, Hex encoded, NOT MATCHED!
1984 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
1985 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
1986}
1987
1988TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001989 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001990 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
1991 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
1992 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
1993 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
1994
1995 // Non-matching cases (character literals, float and double)
1996 EXPECT_TRUE(notMatches("int i = L'a';",
1997 HasIntLiteral)); // this is actually a character
1998 // literal cast to int
1999 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2000 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2001 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2002}
2003
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002004TEST(Matcher, FloatLiterals) {
2005 StatementMatcher HasFloatLiteral = floatLiteral();
2006 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2007 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2008 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2009 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2010 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
2011
2012 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
2013}
2014
Daniel Jasper5901e472012-10-01 13:40:41 +00002015TEST(Matcher, NullPtrLiteral) {
2016 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2017}
2018
Daniel Jasper87c3d362012-09-20 14:12:57 +00002019TEST(Matcher, AsmStatement) {
2020 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2021}
2022
Manuel Klimek04616e42012-07-06 05:48:52 +00002023TEST(Matcher, Conditions) {
2024 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2025
2026 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2027 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2028 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2029 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2030 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2031}
2032
Manuel Klimek909b5c942014-05-27 10:04:12 +00002033TEST(IfStmt, ChildTraversalMatchers) {
2034 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2035 ifStmt(hasThen(boolLiteral(equals(true))))));
2036 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2037 ifStmt(hasThen(boolLiteral(equals(true))))));
2038 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2039 ifStmt(hasElse(boolLiteral(equals(true))))));
2040 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2041 ifStmt(hasElse(boolLiteral(equals(true))))));
2042}
2043
Manuel Klimek04616e42012-07-06 05:48:52 +00002044TEST(MatchBinaryOperator, HasOperatorName) {
2045 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2046
2047 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2048 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2049}
2050
2051TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2052 StatementMatcher OperatorTrueFalse =
2053 binaryOperator(hasLHS(boolLiteral(equals(true))),
2054 hasRHS(boolLiteral(equals(false))));
2055
2056 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2057 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2058 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2059}
2060
2061TEST(MatchBinaryOperator, HasEitherOperand) {
2062 StatementMatcher HasOperand =
2063 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2064
2065 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2066 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2067 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2068}
2069
2070TEST(Matcher, BinaryOperatorTypes) {
2071 // Integration test that verifies the AST provides all binary operators in
2072 // a way we expect.
2073 // FIXME: Operator ','
2074 EXPECT_TRUE(
2075 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2076 EXPECT_TRUE(
2077 matches("bool b; bool c = (b = true);",
2078 binaryOperator(hasOperatorName("="))));
2079 EXPECT_TRUE(
2080 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2081 EXPECT_TRUE(
2082 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2083 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2084 EXPECT_TRUE(
2085 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2086 EXPECT_TRUE(
2087 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2088 EXPECT_TRUE(
2089 matches("int i = 1; int j = (i <<= 2);",
2090 binaryOperator(hasOperatorName("<<="))));
2091 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2092 EXPECT_TRUE(
2093 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2094 EXPECT_TRUE(
2095 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2096 EXPECT_TRUE(
2097 matches("int i = 1; int j = (i >>= 2);",
2098 binaryOperator(hasOperatorName(">>="))));
2099 EXPECT_TRUE(
2100 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2101 EXPECT_TRUE(
2102 matches("int i = 42; int j = (i ^= 42);",
2103 binaryOperator(hasOperatorName("^="))));
2104 EXPECT_TRUE(
2105 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2106 EXPECT_TRUE(
2107 matches("int i = 42; int j = (i %= 42);",
2108 binaryOperator(hasOperatorName("%="))));
2109 EXPECT_TRUE(
2110 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2111 EXPECT_TRUE(
2112 matches("bool b = true && false;",
2113 binaryOperator(hasOperatorName("&&"))));
2114 EXPECT_TRUE(
2115 matches("bool b = true; bool c = (b &= false);",
2116 binaryOperator(hasOperatorName("&="))));
2117 EXPECT_TRUE(
2118 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2119 EXPECT_TRUE(
2120 matches("bool b = true || false;",
2121 binaryOperator(hasOperatorName("||"))));
2122 EXPECT_TRUE(
2123 matches("bool b = true; bool c = (b |= false);",
2124 binaryOperator(hasOperatorName("|="))));
2125 EXPECT_TRUE(
2126 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2127 EXPECT_TRUE(
2128 matches("int i = 42; int j = (i *= 23);",
2129 binaryOperator(hasOperatorName("*="))));
2130 EXPECT_TRUE(
2131 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2132 EXPECT_TRUE(
2133 matches("int i = 42; int j = (i /= 23);",
2134 binaryOperator(hasOperatorName("/="))));
2135 EXPECT_TRUE(
2136 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2137 EXPECT_TRUE(
2138 matches("int i = 42; int j = (i += 23);",
2139 binaryOperator(hasOperatorName("+="))));
2140 EXPECT_TRUE(
2141 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2142 EXPECT_TRUE(
2143 matches("int i = 42; int j = (i -= 23);",
2144 binaryOperator(hasOperatorName("-="))));
2145 EXPECT_TRUE(
2146 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2147 binaryOperator(hasOperatorName("->*"))));
2148 EXPECT_TRUE(
2149 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2150 binaryOperator(hasOperatorName(".*"))));
2151
2152 // Member expressions as operators are not supported in matches.
2153 EXPECT_TRUE(
2154 notMatches("struct A { void x(A *a) { a->x(this); } };",
2155 binaryOperator(hasOperatorName("->"))));
2156
2157 // Initializer assignments are not represented as operator equals.
2158 EXPECT_TRUE(
2159 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2160
2161 // Array indexing is not represented as operator.
2162 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2163
2164 // Overloaded operators do not match at all.
2165 EXPECT_TRUE(notMatches(
2166 "struct A { bool operator&&(const A &a) const { return false; } };"
2167 "void x() { A a, b; a && b; }",
2168 binaryOperator()));
2169}
2170
2171TEST(MatchUnaryOperator, HasOperatorName) {
2172 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2173
2174 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2175 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2176}
2177
2178TEST(MatchUnaryOperator, HasUnaryOperand) {
2179 StatementMatcher OperatorOnFalse =
2180 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2181
2182 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2183 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2184}
2185
2186TEST(Matcher, UnaryOperatorTypes) {
2187 // Integration test that verifies the AST provides all unary operators in
2188 // a way we expect.
2189 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2190 EXPECT_TRUE(
2191 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2192 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2193 EXPECT_TRUE(
2194 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2195 EXPECT_TRUE(
2196 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2197 EXPECT_TRUE(
2198 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2199 EXPECT_TRUE(
2200 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2201 EXPECT_TRUE(
2202 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2203 EXPECT_TRUE(
2204 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2205 EXPECT_TRUE(
2206 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2207
2208 // We don't match conversion operators.
2209 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2210
2211 // Function calls are not represented as operator.
2212 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2213
2214 // Overloaded operators do not match at all.
2215 // FIXME: We probably want to add that.
2216 EXPECT_TRUE(notMatches(
2217 "struct A { bool operator!() const { return false; } };"
2218 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2219}
2220
2221TEST(Matcher, ConditionalOperator) {
2222 StatementMatcher Conditional = conditionalOperator(
2223 hasCondition(boolLiteral(equals(true))),
2224 hasTrueExpression(boolLiteral(equals(false))));
2225
2226 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2227 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2228 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2229
2230 StatementMatcher ConditionalFalse = conditionalOperator(
2231 hasFalseExpression(boolLiteral(equals(false))));
2232
2233 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2234 EXPECT_TRUE(
2235 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2236}
2237
Daniel Jasper1dad1832012-07-10 20:20:19 +00002238TEST(ArraySubscriptMatchers, ArraySubscripts) {
2239 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2240 arraySubscriptExpr()));
2241 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2242 arraySubscriptExpr()));
2243}
2244
2245TEST(ArraySubscriptMatchers, ArrayIndex) {
2246 EXPECT_TRUE(matches(
2247 "int i[2]; void f() { i[1] = 1; }",
2248 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2249 EXPECT_TRUE(matches(
2250 "int i[2]; void f() { 1[i] = 1; }",
2251 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2252 EXPECT_TRUE(notMatches(
2253 "int i[2]; void f() { i[1] = 1; }",
2254 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2255}
2256
2257TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2258 EXPECT_TRUE(matches(
2259 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002260 arraySubscriptExpr(hasBase(implicitCastExpr(
2261 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002262}
2263
Manuel Klimek04616e42012-07-06 05:48:52 +00002264TEST(Matcher, HasNameSupportsNamespaces) {
2265 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002266 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002267 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002268 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002269 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002270 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002271 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002272 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002273 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002274 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002275 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002276 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002277 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002278 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002279 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002280 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002281 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002282 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002283 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002284 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002285 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002286 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002287 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002288 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002289}
2290
2291TEST(Matcher, HasNameSupportsOuterClasses) {
2292 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002293 matches("class A { class B { class C; }; };",
2294 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002295 EXPECT_TRUE(
2296 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002297 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002298 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002299 matches("class A { class B { class C; }; };",
2300 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002301 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002302 matches("class A { class B { class C; }; };",
2303 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002304 EXPECT_TRUE(
2305 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002306 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002307 EXPECT_TRUE(
2308 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002309 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002310 EXPECT_TRUE(
2311 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002312 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002313 EXPECT_TRUE(
2314 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002315 recordDecl(hasName("::C"))));
2316 EXPECT_TRUE(
2317 notMatches("class A { class B { class C; }; };",
2318 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002319 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002320 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002321 EXPECT_TRUE(
2322 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002323 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002324}
2325
2326TEST(Matcher, IsDefinition) {
2327 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002328 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002329 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2330 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2331
2332 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002333 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002334 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2335 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2336
2337 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002338 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002339 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2340 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2341}
2342
2343TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002344 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002345 ofClass(hasName("X")))));
2346
2347 EXPECT_TRUE(
2348 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2349 EXPECT_TRUE(
2350 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2351 Constructor));
2352 EXPECT_TRUE(
2353 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2354 Constructor));
2355}
2356
2357TEST(Matcher, VisitsTemplateInstantiations) {
2358 EXPECT_TRUE(matches(
2359 "class A { public: void x(); };"
2360 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002361 "void f() { B<A> b; b.y(); }",
2362 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002363
2364 EXPECT_TRUE(matches(
2365 "class A { public: void x(); };"
2366 "class C {"
2367 " public:"
2368 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2369 "};"
2370 "void f() {"
2371 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002372 "}",
2373 recordDecl(hasName("C"),
2374 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002375}
2376
Daniel Jasper1dad1832012-07-10 20:20:19 +00002377TEST(Matcher, HandlesNullQualTypes) {
2378 // FIXME: Add a Type matcher so we can replace uses of this
2379 // variable with Type(True())
2380 const TypeMatcher AnyType = anything();
2381
2382 // We don't really care whether this matcher succeeds; we're testing that
2383 // it completes without crashing.
2384 EXPECT_TRUE(matches(
2385 "struct A { };"
2386 "template <typename T>"
2387 "void f(T t) {"
2388 " T local_t(t /* this becomes a null QualType in the AST */);"
2389 "}"
2390 "void g() {"
2391 " f(0);"
2392 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002393 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002394 anyOf(
2395 TypeMatcher(hasDeclaration(anything())),
2396 pointsTo(AnyType),
2397 references(AnyType)
2398 // Other QualType matchers should go here.
2399 ))))));
2400}
2401
Manuel Klimek04616e42012-07-06 05:48:52 +00002402// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002403AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002404 // Make sure all special variables are used: node, match_finder,
2405 // bound_nodes_builder, and the parameter named 'AMatcher'.
2406 return AMatcher.matches(Node, Finder, Builder);
2407}
2408
2409TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002410 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002411
2412 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002413 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002414
2415 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002416 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002417
2418 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002419 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002420}
2421
2422AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +00002423 polymorphicHas,
2424 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2425 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002426 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002427 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002428 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2429 ASTMatchFinder::BK_First);
2430}
2431
2432TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002433 DeclarationMatcher HasClassB =
2434 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002435
2436 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002437 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002438
2439 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002440 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002441
2442 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002443 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002444
2445 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002446 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002447
2448 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2449}
2450
2451TEST(For, FindsForLoops) {
2452 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2453 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002454 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2455 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002456 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002457}
2458
Daniel Jasper4e566c42012-07-12 08:50:38 +00002459TEST(For, ForLoopInternals) {
2460 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2461 forStmt(hasCondition(anything()))));
2462 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2463 forStmt(hasLoopInit(anything()))));
2464}
2465
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002466TEST(For, ForRangeLoopInternals) {
2467 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2468 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002469 EXPECT_TRUE(matches(
2470 "void f(){ int a[] {1, 2}; for (int i : a); }",
2471 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002472}
2473
Daniel Jasper4e566c42012-07-12 08:50:38 +00002474TEST(For, NegativeForLoopInternals) {
2475 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002476 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002477 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2478 forStmt(hasLoopInit(anything()))));
2479}
2480
Manuel Klimek04616e42012-07-06 05:48:52 +00002481TEST(For, ReportsNoFalsePositives) {
2482 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2483 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2484}
2485
2486TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002487 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2488 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2489 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002490}
2491
2492TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2493 // It's not a compound statement just because there's "{}" in the source
2494 // text. This is an AST search, not grep.
2495 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002496 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002497 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002498 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002499}
2500
Daniel Jasper4e566c42012-07-12 08:50:38 +00002501TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002502 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002503 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002504 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002505 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002506 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002507 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002508 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002509 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002510 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2511 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002512}
2513
2514TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2515 // The simplest case: every compound statement is in a function
2516 // definition, and the function body itself must be a compound
2517 // statement.
2518 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002519 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002520}
2521
2522TEST(HasAnySubstatement, IsNotRecursive) {
2523 // It's really "has any immediate substatement".
2524 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002525 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002526}
2527
2528TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2529 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002530 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002531}
2532
2533TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2534 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002535 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002536}
2537
2538TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2539 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002540 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002541 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002542 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002543}
2544
2545TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2546 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002547 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002548 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002549 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002550 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002551 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002552}
2553
2554TEST(StatementCountIs, WorksWithMultipleStatements) {
2555 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002556 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002557}
2558
2559TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2560 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002561 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002562 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002563 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002564 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002565 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002566 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002567 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002568}
2569
2570TEST(Member, WorksInSimplestCase) {
2571 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002572 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002573}
2574
2575TEST(Member, DoesNotMatchTheBaseExpression) {
2576 // Don't pick out the wrong part of the member expression, this should
2577 // be checking the member (name) only.
2578 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002579 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002580}
2581
2582TEST(Member, MatchesInMemberFunctionCall) {
2583 EXPECT_TRUE(matches("void f() {"
2584 " struct { void first() {}; } s;"
2585 " s.first();"
2586 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002587 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002588}
2589
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002590TEST(Member, MatchesMember) {
2591 EXPECT_TRUE(matches(
2592 "struct A { int i; }; void f() { A a; a.i = 2; }",
2593 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2594 EXPECT_TRUE(notMatches(
2595 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2596 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2597}
2598
Daniel Jasper639522c2013-02-25 12:02:08 +00002599TEST(Member, UnderstandsAccess) {
2600 EXPECT_TRUE(matches(
2601 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2602 EXPECT_TRUE(notMatches(
2603 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2604 EXPECT_TRUE(notMatches(
2605 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2606
2607 EXPECT_TRUE(notMatches(
2608 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2609 EXPECT_TRUE(notMatches(
2610 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2611 EXPECT_TRUE(matches(
2612 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2613
2614 EXPECT_TRUE(notMatches(
2615 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2616 EXPECT_TRUE(matches("class A { protected: int i; };",
2617 fieldDecl(isProtected(), hasName("i"))));
2618 EXPECT_TRUE(notMatches(
2619 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2620
2621 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2622 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2623 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2624 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2625}
2626
Dmitri Gribenko06963042012-08-18 00:29:27 +00002627TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002628 // Fails in C++11 mode
2629 EXPECT_TRUE(matchesConditionally(
2630 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2631 "class X { void *operator new(std::size_t); };",
2632 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002633
2634 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002635 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002636
Daniel Jasper5901e472012-10-01 13:40:41 +00002637 // Fails in C++11 mode
2638 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002639 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2640 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002641 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002642}
2643
Manuel Klimek04616e42012-07-06 05:48:52 +00002644TEST(HasObjectExpression, DoesNotMatchMember) {
2645 EXPECT_TRUE(notMatches(
2646 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002647 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002648}
2649
2650TEST(HasObjectExpression, MatchesBaseOfVariable) {
2651 EXPECT_TRUE(matches(
2652 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002653 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002654 EXPECT_TRUE(matches(
2655 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002656 memberExpr(hasObjectExpression(
2657 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002658}
2659
2660TEST(HasObjectExpression,
2661 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2662 EXPECT_TRUE(matches(
2663 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002664 memberExpr(hasObjectExpression(
2665 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002666 EXPECT_TRUE(matches(
2667 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002668 memberExpr(hasObjectExpression(
2669 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002670}
2671
2672TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002673 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2674 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2675 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2676 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002677}
2678
2679TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002680 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002681}
2682
2683TEST(IsConstQualified, MatchesConstInt) {
2684 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002685 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002686}
2687
2688TEST(IsConstQualified, MatchesConstPointer) {
2689 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002690 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002691}
2692
2693TEST(IsConstQualified, MatchesThroughTypedef) {
2694 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002695 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002696 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002697 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002698}
2699
2700TEST(IsConstQualified, DoesNotMatchInappropriately) {
2701 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002702 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002703 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002704 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002705}
2706
Sam Panzer80c13772012-08-16 16:58:10 +00002707TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002708 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2709 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2710 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2711 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002712}
2713TEST(CastExpression, MatchesImplicitCasts) {
2714 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002715 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002716 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002717 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002718}
2719
2720TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002721 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2722 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2723 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2724 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002725}
2726
Manuel Klimek04616e42012-07-06 05:48:52 +00002727TEST(ReinterpretCast, MatchesSimpleCase) {
2728 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002729 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002730}
2731
2732TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002733 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002734 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002735 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002736 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002737 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002738 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2739 "B b;"
2740 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002741 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002742}
2743
2744TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002745 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002746 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002747 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002748}
2749
2750TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002751 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002752 EXPECT_TRUE(
2753 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002754 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002755 EXPECT_TRUE(
2756 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002757 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002758}
2759
2760TEST(DynamicCast, MatchesSimpleCase) {
2761 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2762 "B b;"
2763 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002764 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002765}
2766
2767TEST(StaticCast, MatchesSimpleCase) {
2768 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002769 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002770}
2771
2772TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002773 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002774 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002775 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002776 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002777 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002778 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2779 "B b;"
2780 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002781 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002782}
2783
Daniel Jasper417f7762012-09-18 13:36:17 +00002784TEST(CStyleCast, MatchesSimpleCase) {
2785 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2786}
2787
2788TEST(CStyleCast, DoesNotMatchOtherCasts) {
2789 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2790 "char q, *r = const_cast<char*>(&q);"
2791 "void* s = reinterpret_cast<char*>(&s);"
2792 "struct B { virtual ~B() {} }; struct D : B {};"
2793 "B b;"
2794 "D* t = dynamic_cast<D*>(&b);",
2795 cStyleCastExpr()));
2796}
2797
Manuel Klimek04616e42012-07-06 05:48:52 +00002798TEST(HasDestinationType, MatchesSimpleCase) {
2799 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002800 staticCastExpr(hasDestinationType(
2801 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002802}
2803
Sam Panzer80c13772012-08-16 16:58:10 +00002804TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2805 // This test creates an implicit const cast.
2806 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002807 implicitCastExpr(
2808 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002809 // This test creates an implicit array-to-pointer cast.
2810 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002811 implicitCastExpr(hasImplicitDestinationType(
2812 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002813}
2814
2815TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2816 // This test creates an implicit cast from int to char.
2817 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002818 implicitCastExpr(hasImplicitDestinationType(
2819 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002820 // This test creates an implicit array-to-pointer cast.
2821 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002822 implicitCastExpr(hasImplicitDestinationType(
2823 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002824}
2825
2826TEST(ImplicitCast, MatchesSimpleCase) {
2827 // This test creates an implicit const cast.
2828 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002829 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002830 // This test creates an implicit cast from int to char.
2831 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002832 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002833 // This test creates an implicit array-to-pointer cast.
2834 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002835 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002836}
2837
2838TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002839 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002840 // are present, and that it ignores explicit and paren casts.
2841
2842 // These two test cases have no casts.
2843 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002844 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002845 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002846 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002847
2848 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002849 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002850 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002851 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002852
2853 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002854 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002855}
2856
2857TEST(IgnoringImpCasts, MatchesImpCasts) {
2858 // This test checks that ignoringImpCasts matches when implicit casts are
2859 // present and its inner matcher alone does not match.
2860 // Note that this test creates an implicit const cast.
2861 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002862 varDecl(hasInitializer(ignoringImpCasts(
2863 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002864 // This test creates an implict cast from int to char.
2865 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002866 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002867 integerLiteral(equals(0)))))));
2868}
2869
2870TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2871 // These tests verify that ignoringImpCasts does not match if the inner
2872 // matcher does not match.
2873 // Note that the first test creates an implicit const cast.
2874 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002875 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002876 unless(anything()))))));
2877 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002878 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002879 unless(anything()))))));
2880
2881 // These tests verify that ignoringImplictCasts does not look through explicit
2882 // casts or parentheses.
2883 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002884 varDecl(hasInitializer(ignoringImpCasts(
2885 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002886 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002887 varDecl(hasInitializer(ignoringImpCasts(
2888 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002889 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002890 varDecl(hasInitializer(ignoringImpCasts(
2891 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002892 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002893 varDecl(hasInitializer(ignoringImpCasts(
2894 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002895}
2896
2897TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2898 // This test verifies that expressions that do not have implicit casts
2899 // still match the inner matcher.
2900 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002901 varDecl(hasInitializer(ignoringImpCasts(
2902 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002903}
2904
2905TEST(IgnoringParenCasts, MatchesParenCasts) {
2906 // This test checks that ignoringParenCasts matches when parentheses and/or
2907 // casts are present and its inner matcher alone does not match.
2908 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002909 varDecl(hasInitializer(ignoringParenCasts(
2910 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002911 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002912 varDecl(hasInitializer(ignoringParenCasts(
2913 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002914
2915 // This test creates an implict cast from int to char in addition to the
2916 // parentheses.
2917 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002918 varDecl(hasInitializer(ignoringParenCasts(
2919 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002920
2921 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002922 varDecl(hasInitializer(ignoringParenCasts(
2923 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002924 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002925 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002926 integerLiteral(equals(0)))))));
2927}
2928
2929TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
2930 // This test verifies that expressions that do not have any casts still match.
2931 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002932 varDecl(hasInitializer(ignoringParenCasts(
2933 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002934}
2935
2936TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
2937 // These tests verify that ignoringImpCasts does not match if the inner
2938 // matcher does not match.
2939 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002940 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002941 unless(anything()))))));
2942
2943 // This test creates an implicit cast from int to char in addition to the
2944 // parentheses.
2945 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002946 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002947 unless(anything()))))));
2948
2949 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002950 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002951 unless(anything()))))));
2952}
2953
2954TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
2955 // This test checks that ignoringParenAndImpCasts matches when
2956 // parentheses and/or implicit casts are present and its inner matcher alone
2957 // does not match.
2958 // Note that this test creates an implicit const cast.
2959 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002960 varDecl(hasInitializer(ignoringParenImpCasts(
2961 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002962 // This test creates an implicit cast from int to char.
2963 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002964 varDecl(hasInitializer(ignoringParenImpCasts(
2965 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002966}
2967
2968TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
2969 // This test verifies that expressions that do not have parentheses or
2970 // implicit casts still match.
2971 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002972 varDecl(hasInitializer(ignoringParenImpCasts(
2973 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002974 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002975 varDecl(hasInitializer(ignoringParenImpCasts(
2976 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002977}
2978
2979TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
2980 // These tests verify that ignoringParenImpCasts does not match if
2981 // the inner matcher does not match.
2982 // This test creates an implicit cast.
2983 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002984 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002985 unless(anything()))))));
2986 // These tests verify that ignoringParenAndImplictCasts does not look
2987 // through explicit casts.
2988 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002989 varDecl(hasInitializer(ignoringParenImpCasts(
2990 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002991 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002992 varDecl(hasInitializer(ignoringParenImpCasts(
2993 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002994 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002995 varDecl(hasInitializer(ignoringParenImpCasts(
2996 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002997}
2998
Manuel Klimeke9235692012-07-25 10:02:02 +00002999TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003000 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3001 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003002 implicitCastExpr(
3003 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003004}
3005
Manuel Klimeke9235692012-07-25 10:02:02 +00003006TEST(HasSourceExpression, MatchesExplicitCasts) {
3007 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003008 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003009 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003010 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003011}
3012
Manuel Klimek04616e42012-07-06 05:48:52 +00003013TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003014 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003015}
3016
3017TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003018 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003019}
3020
3021TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003022 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003023}
3024
3025TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003026 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003027}
3028
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003029TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3030 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3031 "const Foo f = Foo();",
3032 varDecl(hasInitializer(exprWithCleanups()))));
3033 EXPECT_FALSE(matches("struct Foo { };"
3034 "const Foo f = Foo();",
3035 varDecl(hasInitializer(exprWithCleanups()))));
3036}
3037
Daniel Jasper1dad1832012-07-10 20:20:19 +00003038TEST(InitListExpression, MatchesInitListExpression) {
3039 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3040 initListExpr(hasType(asString("int [2]")))));
3041 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003042 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003043}
3044
3045TEST(UsingDeclaration, MatchesUsingDeclarations) {
3046 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3047 usingDecl()));
3048}
3049
3050TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3051 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3052 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3053}
3054
3055TEST(UsingDeclaration, MatchesSpecificTarget) {
3056 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3057 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003058 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003059 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3060 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003061 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003062}
3063
3064TEST(UsingDeclaration, ThroughUsingDeclaration) {
3065 EXPECT_TRUE(matches(
3066 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003067 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003068 EXPECT_TRUE(notMatches(
3069 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003070 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003071}
3072
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003073TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3074 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3075 usingDirectiveDecl()));
3076 EXPECT_FALSE(
3077 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3078}
3079
Sam Panzerd624bfb2012-08-16 17:20:59 +00003080TEST(SingleDecl, IsSingleDecl) {
3081 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003082 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003083 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3084 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3085 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3086 SingleDeclStmt));
3087}
3088
3089TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003090 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003091
3092 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003093 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003094 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003095 declStmt(containsDeclaration(0, MatchesInit),
3096 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003097 unsigned WrongIndex = 42;
3098 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003099 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003100 MatchesInit))));
3101}
3102
3103TEST(DeclCount, DeclCountIsCorrect) {
3104 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003105 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003106 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003107 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003108 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003109 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003110}
3111
Manuel Klimek04616e42012-07-06 05:48:52 +00003112TEST(While, MatchesWhileLoops) {
3113 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3114 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3115 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3116}
3117
3118TEST(Do, MatchesDoLoops) {
3119 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3120 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3121}
3122
3123TEST(Do, DoesNotMatchWhileLoops) {
3124 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3125}
3126
3127TEST(SwitchCase, MatchesCase) {
3128 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3129 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3130 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3131 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3132}
3133
Daniel Jasper87c3d362012-09-20 14:12:57 +00003134TEST(SwitchCase, MatchesSwitch) {
3135 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3136 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3137 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3138 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3139}
3140
Peter Collingbourne3154a102013-05-10 11:52:02 +00003141TEST(SwitchCase, MatchesEachCase) {
3142 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3143 switchStmt(forEachSwitchCase(caseStmt()))));
3144 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3145 switchStmt(forEachSwitchCase(caseStmt()))));
3146 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3147 switchStmt(forEachSwitchCase(caseStmt()))));
3148 EXPECT_TRUE(notMatches(
3149 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3150 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3151 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3152 switchStmt(forEachSwitchCase(
3153 caseStmt(hasCaseConstant(integerLiteral()))))));
3154 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3155 switchStmt(forEachSwitchCase(
3156 caseStmt(hasCaseConstant(integerLiteral()))))));
3157 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3158 switchStmt(forEachSwitchCase(
3159 caseStmt(hasCaseConstant(integerLiteral()))))));
3160 EXPECT_TRUE(matchAndVerifyResultTrue(
3161 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3162 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3163 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3164}
3165
Manuel Klimekba46fc02013-07-19 11:50:54 +00003166TEST(ForEachConstructorInitializer, MatchesInitializers) {
3167 EXPECT_TRUE(matches(
3168 "struct X { X() : i(42), j(42) {} int i, j; };",
3169 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3170}
3171
Daniel Jasper87c3d362012-09-20 14:12:57 +00003172TEST(ExceptionHandling, SimpleCases) {
3173 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3174 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3175 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3176 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3177 throwExpr()));
3178 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3179 throwExpr()));
3180}
3181
Manuel Klimek04616e42012-07-06 05:48:52 +00003182TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3183 EXPECT_TRUE(notMatches(
3184 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003185 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003186 EXPECT_TRUE(notMatches(
3187 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003188 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003189}
3190
3191TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3192 EXPECT_TRUE(matches(
3193 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003194 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003195}
3196
3197TEST(ForEach, BindsOneNode) {
3198 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003199 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003200 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003201}
3202
3203TEST(ForEach, BindsMultipleNodes) {
3204 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003205 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003206 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003207}
3208
3209TEST(ForEach, BindsRecursiveCombinations) {
3210 EXPECT_TRUE(matchAndVerifyResultTrue(
3211 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003212 recordDecl(hasName("C"),
3213 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003214 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003215}
3216
3217TEST(ForEachDescendant, BindsOneNode) {
3218 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003219 recordDecl(hasName("C"),
3220 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003221 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003222}
3223
Daniel Jasper94a56852012-11-16 18:39:22 +00003224TEST(ForEachDescendant, NestedForEachDescendant) {
3225 DeclarationMatcher m = recordDecl(
3226 isDefinition(), decl().bind("x"), hasName("C"));
3227 EXPECT_TRUE(matchAndVerifyResultTrue(
3228 "class A { class B { class C {}; }; };",
3229 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3230 new VerifyIdIsBoundTo<Decl>("x", "C")));
3231
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003232 // Check that a partial match of 'm' that binds 'x' in the
3233 // first part of anyOf(m, anything()) will not overwrite the
3234 // binding created by the earlier binding in the hasDescendant.
3235 EXPECT_TRUE(matchAndVerifyResultTrue(
3236 "class A { class B { class C {}; }; };",
3237 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3238 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003239}
3240
Manuel Klimek04616e42012-07-06 05:48:52 +00003241TEST(ForEachDescendant, BindsMultipleNodes) {
3242 EXPECT_TRUE(matchAndVerifyResultTrue(
3243 "class C { class D { int x; int y; }; "
3244 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003245 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003246 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003247}
3248
3249TEST(ForEachDescendant, BindsRecursiveCombinations) {
3250 EXPECT_TRUE(matchAndVerifyResultTrue(
3251 "class C { class D { "
3252 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003253 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3254 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003255 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003256}
3257
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003258TEST(ForEachDescendant, BindsCombinations) {
3259 EXPECT_TRUE(matchAndVerifyResultTrue(
3260 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3261 "(true) {} }",
3262 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3263 forEachDescendant(whileStmt().bind("while"))),
3264 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3265}
3266
3267TEST(Has, DoesNotDeleteBindings) {
3268 EXPECT_TRUE(matchAndVerifyResultTrue(
3269 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3270 new VerifyIdIsBoundTo<Decl>("x", 1)));
3271}
3272
3273TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3274 // Those matchers cover all the cases where an inner matcher is called
3275 // and there is not a 1:1 relationship between the match of the outer
3276 // matcher and the match of the inner matcher.
3277 // The pattern to look for is:
3278 // ... return InnerMatcher.matches(...); ...
3279 // In which case no special handling is needed.
3280 //
3281 // On the other hand, if there are multiple alternative matches
3282 // (for example forEach*) or matches might be discarded (for example has*)
3283 // the implementation must make sure that the discarded matches do not
3284 // affect the bindings.
3285 // When new such matchers are added, add a test here that:
3286 // - matches a simple node, and binds it as the first thing in the matcher:
3287 // recordDecl(decl().bind("x"), hasName("X")))
3288 // - uses the matcher under test afterwards in a way that not the first
3289 // alternative is matched; for anyOf, that means the first branch
3290 // would need to return false; for hasAncestor, it means that not
3291 // the direct parent matches the inner matcher.
3292
3293 EXPECT_TRUE(matchAndVerifyResultTrue(
3294 "class X { int y; };",
3295 recordDecl(
3296 recordDecl().bind("x"), hasName("::X"),
3297 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3298 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3299 EXPECT_TRUE(matchAndVerifyResultTrue(
3300 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3301 anyOf(unless(anything()), anything())),
3302 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3303 EXPECT_TRUE(matchAndVerifyResultTrue(
3304 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3305 classTemplateSpecializationDecl(
3306 decl().bind("x"),
3307 hasAnyTemplateArgument(refersToType(asString("int")))),
3308 new VerifyIdIsBoundTo<Decl>("x", 1)));
3309 EXPECT_TRUE(matchAndVerifyResultTrue(
3310 "class X { void f(); void g(); };",
3311 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3312 new VerifyIdIsBoundTo<Decl>("x", 1)));
3313 EXPECT_TRUE(matchAndVerifyResultTrue(
3314 "class X { X() : a(1), b(2) {} double a; int b; };",
3315 recordDecl(decl().bind("x"),
3316 has(constructorDecl(
3317 hasAnyConstructorInitializer(forField(hasName("b")))))),
3318 new VerifyIdIsBoundTo<Decl>("x", 1)));
3319 EXPECT_TRUE(matchAndVerifyResultTrue(
3320 "void x(int, int) { x(0, 42); }",
3321 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3322 new VerifyIdIsBoundTo<Expr>("x", 1)));
3323 EXPECT_TRUE(matchAndVerifyResultTrue(
3324 "void x(int, int y) {}",
3325 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3326 new VerifyIdIsBoundTo<Decl>("x", 1)));
3327 EXPECT_TRUE(matchAndVerifyResultTrue(
3328 "void x() { return; if (true) {} }",
3329 functionDecl(decl().bind("x"),
3330 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3331 new VerifyIdIsBoundTo<Decl>("x", 1)));
3332 EXPECT_TRUE(matchAndVerifyResultTrue(
3333 "namespace X { void b(int); void b(); }"
3334 "using X::b;",
3335 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3336 functionDecl(parameterCountIs(1))))),
3337 new VerifyIdIsBoundTo<Decl>("x", 1)));
3338 EXPECT_TRUE(matchAndVerifyResultTrue(
3339 "class A{}; class B{}; class C : B, A {};",
3340 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3341 new VerifyIdIsBoundTo<Decl>("x", 1)));
3342 EXPECT_TRUE(matchAndVerifyResultTrue(
3343 "class A{}; typedef A B; typedef A C; typedef A D;"
3344 "class E : A {};",
3345 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3346 new VerifyIdIsBoundTo<Decl>("x", 1)));
3347 EXPECT_TRUE(matchAndVerifyResultTrue(
3348 "class A { class B { void f() {} }; };",
3349 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3350 new VerifyIdIsBoundTo<Decl>("x", 1)));
3351 EXPECT_TRUE(matchAndVerifyResultTrue(
3352 "template <typename T> struct A { struct B {"
3353 " void f() { if(true) {} }"
3354 "}; };"
3355 "void t() { A<int>::B b; b.f(); }",
3356 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3357 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3358 EXPECT_TRUE(matchAndVerifyResultTrue(
3359 "class A {};",
3360 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3361 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003362 EXPECT_TRUE(matchAndVerifyResultTrue(
3363 "class A { A() : s(), i(42) {} const char *s; int i; };",
3364 constructorDecl(hasName("::A::A"), decl().bind("x"),
3365 forEachConstructorInitializer(forField(hasName("i")))),
3366 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003367}
3368
Daniel Jasper33806cd2012-11-11 22:14:55 +00003369TEST(ForEachDescendant, BindsCorrectNodes) {
3370 EXPECT_TRUE(matchAndVerifyResultTrue(
3371 "class C { void f(); int i; };",
3372 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3373 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3374 EXPECT_TRUE(matchAndVerifyResultTrue(
3375 "class C { void f() {} int i; };",
3376 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3377 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3378}
3379
Manuel Klimekabf43712013-02-04 10:59:20 +00003380TEST(FindAll, BindsNodeOnMatch) {
3381 EXPECT_TRUE(matchAndVerifyResultTrue(
3382 "class A {};",
3383 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3384 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3385}
3386
3387TEST(FindAll, BindsDescendantNodeOnMatch) {
3388 EXPECT_TRUE(matchAndVerifyResultTrue(
3389 "class A { int a; int b; };",
3390 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3391 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3392}
3393
3394TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3395 EXPECT_TRUE(matchAndVerifyResultTrue(
3396 "class A { int a; int b; };",
3397 recordDecl(hasName("::A"),
3398 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3399 fieldDecl().bind("v"))))),
3400 new VerifyIdIsBoundTo<Decl>("v", 3)));
3401
3402 EXPECT_TRUE(matchAndVerifyResultTrue(
3403 "class A { class B {}; class C {}; };",
3404 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3405 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3406}
3407
Manuel Klimek88b95872013-02-04 09:42:38 +00003408TEST(EachOf, TriggersForEachMatch) {
3409 EXPECT_TRUE(matchAndVerifyResultTrue(
3410 "class A { int a; int b; };",
3411 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3412 has(fieldDecl(hasName("b")).bind("v")))),
3413 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3414}
3415
3416TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3417 EXPECT_TRUE(matchAndVerifyResultTrue(
3418 "class A { int a; int c; };",
3419 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3420 has(fieldDecl(hasName("b")).bind("v")))),
3421 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3422 EXPECT_TRUE(matchAndVerifyResultTrue(
3423 "class A { int c; int b; };",
3424 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3425 has(fieldDecl(hasName("b")).bind("v")))),
3426 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3427 EXPECT_TRUE(notMatches(
3428 "class A { int c; int d; };",
3429 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3430 has(fieldDecl(hasName("b")).bind("v"))))));
3431}
Manuel Klimek04616e42012-07-06 05:48:52 +00003432
3433TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3434 // Make sure that we can both match the class by name (::X) and by the type
3435 // the template was instantiated with (via a field).
3436
3437 EXPECT_TRUE(matches(
3438 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003439 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003440
3441 EXPECT_TRUE(matches(
3442 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003443 recordDecl(isTemplateInstantiation(), hasDescendant(
3444 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003445}
3446
3447TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3448 EXPECT_TRUE(matches(
3449 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003450 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003451 isTemplateInstantiation())));
3452}
3453
3454TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3455 EXPECT_TRUE(matches(
3456 "template <typename T> class X { T t; }; class A {};"
3457 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003458 recordDecl(isTemplateInstantiation(), hasDescendant(
3459 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003460}
3461
3462TEST(IsTemplateInstantiation,
3463 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3464 EXPECT_TRUE(matches(
3465 "template <typename T> class X {};"
3466 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003467 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003468}
3469
3470TEST(IsTemplateInstantiation,
3471 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3472 EXPECT_TRUE(matches(
3473 "class A {};"
3474 "class X {"
3475 " template <typename U> class Y { U u; };"
3476 " Y<A> y;"
3477 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003478 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003479}
3480
3481TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3482 // FIXME: Figure out whether this makes sense. It doesn't affect the
3483 // normal use case as long as the uppermost instantiation always is marked
3484 // as template instantiation, but it might be confusing as a predicate.
3485 EXPECT_TRUE(matches(
3486 "class A {};"
3487 "template <typename T> class X {"
3488 " template <typename U> class Y { U u; };"
3489 " Y<T> y;"
3490 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003491 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003492}
3493
3494TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3495 EXPECT_TRUE(notMatches(
3496 "template <typename T> class X {}; class A {};"
3497 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003498 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003499}
3500
3501TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3502 EXPECT_TRUE(notMatches(
3503 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003504 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003505}
3506
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003507TEST(IsInstantiated, MatchesInstantiation) {
3508 EXPECT_TRUE(
3509 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3510 recordDecl(isInstantiated())));
3511}
3512
3513TEST(IsInstantiated, NotMatchesDefinition) {
3514 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3515 recordDecl(isInstantiated())));
3516}
3517
3518TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3519 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3520 "class Y { A<int> a; }; Y y;",
3521 declStmt(isInTemplateInstantiation())));
3522}
3523
3524TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3525 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3526 declStmt(isInTemplateInstantiation())));
3527}
3528
3529TEST(IsInstantiated, MatchesFunctionInstantiation) {
3530 EXPECT_TRUE(
3531 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3532 functionDecl(isInstantiated())));
3533}
3534
3535TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3536 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3537 varDecl(isInstantiated())));
3538}
3539
3540TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3541 EXPECT_TRUE(
3542 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3543 declStmt(isInTemplateInstantiation())));
3544}
3545
3546TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3547 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3548 declStmt(isInTemplateInstantiation())));
3549}
3550
3551TEST(IsInTemplateInstantiation, Sharing) {
3552 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3553 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3554 // and makes the matcher behave in non-obvious ways.
3555 EXPECT_TRUE(notMatches(
3556 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3557 Matcher));
3558 EXPECT_TRUE(matches(
3559 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3560 Matcher));
3561}
3562
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003563TEST(IsExplicitTemplateSpecialization,
3564 DoesNotMatchPrimaryTemplate) {
3565 EXPECT_TRUE(notMatches(
3566 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003567 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003568 EXPECT_TRUE(notMatches(
3569 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003570 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003571}
3572
3573TEST(IsExplicitTemplateSpecialization,
3574 DoesNotMatchExplicitTemplateInstantiations) {
3575 EXPECT_TRUE(notMatches(
3576 "template <typename T> class X {};"
3577 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003578 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003579 EXPECT_TRUE(notMatches(
3580 "template <typename T> void f(T t) {}"
3581 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003582 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003583}
3584
3585TEST(IsExplicitTemplateSpecialization,
3586 DoesNotMatchImplicitTemplateInstantiations) {
3587 EXPECT_TRUE(notMatches(
3588 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003589 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003590 EXPECT_TRUE(notMatches(
3591 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003592 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003593}
3594
3595TEST(IsExplicitTemplateSpecialization,
3596 MatchesExplicitTemplateSpecializations) {
3597 EXPECT_TRUE(matches(
3598 "template <typename T> class X {};"
3599 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003600 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003601 EXPECT_TRUE(matches(
3602 "template <typename T> void f(T t) {}"
3603 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003604 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003605}
3606
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003607TEST(HasAncenstor, MatchesDeclarationAncestors) {
3608 EXPECT_TRUE(matches(
3609 "class A { class B { class C {}; }; };",
3610 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3611}
3612
3613TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3614 EXPECT_TRUE(notMatches(
3615 "class A { class B { class C {}; }; };",
3616 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3617}
3618
3619TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3620 EXPECT_TRUE(matches(
3621 "class A { class B { void f() { C c; } class C {}; }; };",
3622 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3623 hasAncestor(recordDecl(hasName("A"))))))));
3624}
3625
3626TEST(HasAncenstor, MatchesStatementAncestors) {
3627 EXPECT_TRUE(matches(
3628 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003629 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003630}
3631
3632TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3633 EXPECT_TRUE(matches(
3634 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003635 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003636}
3637
3638TEST(HasAncestor, BindsRecursiveCombinations) {
3639 EXPECT_TRUE(matchAndVerifyResultTrue(
3640 "class C { class D { class E { class F { int y; }; }; }; };",
3641 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003642 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003643}
3644
3645TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3646 EXPECT_TRUE(matchAndVerifyResultTrue(
3647 "class C { class D { class E { class F { int y; }; }; }; };",
3648 fieldDecl(hasAncestor(
3649 decl(
3650 hasDescendant(recordDecl(isDefinition(),
3651 hasAncestor(recordDecl())))
3652 ).bind("d")
3653 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003654 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003655}
3656
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003657TEST(HasAncestor, MatchesClosestAncestor) {
3658 EXPECT_TRUE(matchAndVerifyResultTrue(
3659 "template <typename T> struct C {"
3660 " void f(int) {"
3661 " struct I { void g(T) { int x; } } i; i.g(42);"
3662 " }"
3663 "};"
3664 "template struct C<int>;",
3665 varDecl(hasName("x"),
3666 hasAncestor(functionDecl(hasParameter(
3667 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3668 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3669}
3670
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003671TEST(HasAncestor, MatchesInTemplateInstantiations) {
3672 EXPECT_TRUE(matches(
3673 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3674 "A<int>::B::C a;",
3675 fieldDecl(hasType(asString("int")),
3676 hasAncestor(recordDecl(hasName("A"))))));
3677}
3678
3679TEST(HasAncestor, MatchesInImplicitCode) {
3680 EXPECT_TRUE(matches(
3681 "struct X {}; struct A { A() {} X x; };",
3682 constructorDecl(
3683 hasAnyConstructorInitializer(withInitializer(expr(
3684 hasAncestor(recordDecl(hasName("A")))))))));
3685}
3686
Daniel Jasper632aea92012-10-22 16:26:51 +00003687TEST(HasParent, MatchesOnlyParent) {
3688 EXPECT_TRUE(matches(
3689 "void f() { if (true) { int x = 42; } }",
3690 compoundStmt(hasParent(ifStmt()))));
3691 EXPECT_TRUE(notMatches(
3692 "void f() { for (;;) { int x = 42; } }",
3693 compoundStmt(hasParent(ifStmt()))));
3694 EXPECT_TRUE(notMatches(
3695 "void f() { if (true) for (;;) { int x = 42; } }",
3696 compoundStmt(hasParent(ifStmt()))));
3697}
3698
Manuel Klimekc844a462012-12-06 14:42:48 +00003699TEST(HasAncestor, MatchesAllAncestors) {
3700 EXPECT_TRUE(matches(
3701 "template <typename T> struct C { static void f() { 42; } };"
3702 "void t() { C<int>::f(); }",
3703 integerLiteral(
3704 equals(42),
3705 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3706 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3707}
3708
3709TEST(HasParent, MatchesAllParents) {
3710 EXPECT_TRUE(matches(
3711 "template <typename T> struct C { static void f() { 42; } };"
3712 "void t() { C<int>::f(); }",
3713 integerLiteral(
3714 equals(42),
3715 hasParent(compoundStmt(hasParent(functionDecl(
3716 hasParent(recordDecl(isTemplateInstantiation())))))))));
3717 EXPECT_TRUE(matches(
3718 "template <typename T> struct C { static void f() { 42; } };"
3719 "void t() { C<int>::f(); }",
3720 integerLiteral(
3721 equals(42),
3722 hasParent(compoundStmt(hasParent(functionDecl(
3723 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3724 EXPECT_TRUE(matches(
3725 "template <typename T> struct C { static void f() { 42; } };"
3726 "void t() { C<int>::f(); }",
3727 integerLiteral(equals(42),
3728 hasParent(compoundStmt(allOf(
3729 hasParent(functionDecl(
3730 hasParent(recordDecl(isTemplateInstantiation())))),
3731 hasParent(functionDecl(hasParent(recordDecl(
3732 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003733 EXPECT_TRUE(
3734 notMatches("template <typename T> struct C { static void f() {} };"
3735 "void t() { C<int>::f(); }",
3736 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003737}
3738
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003739TEST(HasParent, NoDuplicateParents) {
3740 class HasDuplicateParents : public BoundNodesCallback {
3741 public:
3742 bool run(const BoundNodes *Nodes) override { return false; }
3743 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3744 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3745 std::set<const void *> Parents;
3746 for (const auto &Parent : Context->getParents(*Node)) {
3747 if (!Parents.insert(Parent.getMemoizationData()).second) {
3748 return true;
3749 }
3750 }
3751 return false;
3752 }
3753 };
3754 EXPECT_FALSE(matchAndVerifyResultTrue(
3755 "template <typename T> int Foo() { return 1 + 2; }\n"
3756 "int x = Foo<int>() + Foo<unsigned>();",
3757 stmt().bind("node"), new HasDuplicateParents()));
3758}
3759
Daniel Jasper516b02e2012-10-17 08:52:59 +00003760TEST(TypeMatching, MatchesTypes) {
3761 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3762}
3763
3764TEST(TypeMatching, MatchesArrayTypes) {
3765 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3766 EXPECT_TRUE(matches("int a[42];", arrayType()));
3767 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3768
3769 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3770 arrayType(hasElementType(builtinType()))));
3771
3772 EXPECT_TRUE(matches(
3773 "int const a[] = { 2, 3 };",
3774 qualType(arrayType(hasElementType(builtinType())))));
3775 EXPECT_TRUE(matches(
3776 "int const a[] = { 2, 3 };",
3777 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3778 EXPECT_TRUE(matches(
3779 "typedef const int T; T x[] = { 1, 2 };",
3780 qualType(isConstQualified(), arrayType())));
3781
3782 EXPECT_TRUE(notMatches(
3783 "int a[] = { 2, 3 };",
3784 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3785 EXPECT_TRUE(notMatches(
3786 "int a[] = { 2, 3 };",
3787 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3788 EXPECT_TRUE(notMatches(
3789 "int const a[] = { 2, 3 };",
3790 qualType(arrayType(hasElementType(builtinType())),
3791 unless(isConstQualified()))));
3792
3793 EXPECT_TRUE(matches("int a[2];",
3794 constantArrayType(hasElementType(builtinType()))));
3795 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3796}
3797
3798TEST(TypeMatching, MatchesComplexTypes) {
3799 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3800 EXPECT_TRUE(matches(
3801 "_Complex float f;",
3802 complexType(hasElementType(builtinType()))));
3803 EXPECT_TRUE(notMatches(
3804 "_Complex float f;",
3805 complexType(hasElementType(isInteger()))));
3806}
3807
3808TEST(TypeMatching, MatchesConstantArrayTypes) {
3809 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3810 EXPECT_TRUE(notMatches(
3811 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3812 constantArrayType(hasElementType(builtinType()))));
3813
3814 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3815 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3816 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3817}
3818
3819TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3820 EXPECT_TRUE(matches(
3821 "template <typename T, int Size> class array { T data[Size]; };",
3822 dependentSizedArrayType()));
3823 EXPECT_TRUE(notMatches(
3824 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3825 dependentSizedArrayType()));
3826}
3827
3828TEST(TypeMatching, MatchesIncompleteArrayType) {
3829 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3830 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3831
3832 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3833 incompleteArrayType()));
3834}
3835
3836TEST(TypeMatching, MatchesVariableArrayType) {
3837 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3838 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3839
3840 EXPECT_TRUE(matches(
3841 "void f(int b) { int a[b]; }",
3842 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3843 varDecl(hasName("b")))))))));
3844}
3845
3846TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003847 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3848 llvm::Triple::Win32) {
3849 // FIXME: Make this work for MSVC.
3850 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003851
David Majnemer197e2102014-03-05 06:32:38 +00003852 EXPECT_TRUE(matches("_Atomic(int) i;",
3853 atomicType(hasValueType(isInteger()))));
3854 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3855 atomicType(hasValueType(isInteger()))));
3856 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003857}
3858
3859TEST(TypeMatching, MatchesAutoTypes) {
3860 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3861 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3862 autoType()));
3863
Richard Smith061f1e22013-04-30 21:23:01 +00003864 // FIXME: Matching against the type-as-written can't work here, because the
3865 // type as written was not deduced.
3866 //EXPECT_TRUE(matches("auto a = 1;",
3867 // autoType(hasDeducedType(isInteger()))));
3868 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3869 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003870}
3871
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00003872TEST(TypeMatching, MatchesFunctionTypes) {
3873 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3874 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3875}
3876
Edwin Vaneec074802013-04-01 18:33:34 +00003877TEST(TypeMatching, MatchesParenType) {
3878 EXPECT_TRUE(
3879 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3880 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3881
3882 EXPECT_TRUE(matches(
3883 "int (*ptr_to_func)(int);",
3884 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3885 EXPECT_TRUE(notMatches(
3886 "int (*ptr_to_array)[4];",
3887 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3888}
3889
Daniel Jasper516b02e2012-10-17 08:52:59 +00003890TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003891 // FIXME: Reactive when these tests can be more specific (not matching
3892 // implicit code on certain platforms), likely when we have hasDescendant for
3893 // Types/TypeLocs.
3894 //EXPECT_TRUE(matchAndVerifyResultTrue(
3895 // "int* a;",
3896 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3897 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3898 //EXPECT_TRUE(matchAndVerifyResultTrue(
3899 // "int* a;",
3900 // pointerTypeLoc().bind("loc"),
3901 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003902 EXPECT_TRUE(matches(
3903 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003904 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003905 EXPECT_TRUE(matches(
3906 "int** a;",
3907 loc(pointerType(pointee(pointerType())))));
3908 EXPECT_TRUE(matches(
3909 "int* b; int* * const a = &b;",
3910 loc(qualType(isConstQualified(), pointerType()))));
3911
3912 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00003913 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3914 hasType(blockPointerType()))));
3915 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3916 hasType(memberPointerType()))));
3917 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3918 hasType(pointerType()))));
3919 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3920 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003921 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3922 hasType(lValueReferenceType()))));
3923 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3924 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003925
Daniel Jasper7943eb52012-10-17 13:35:36 +00003926 Fragment = "int *ptr;";
3927 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3928 hasType(blockPointerType()))));
3929 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3930 hasType(memberPointerType()))));
3931 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3932 hasType(pointerType()))));
3933 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3934 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003935
Daniel Jasper7943eb52012-10-17 13:35:36 +00003936 Fragment = "int a; int &ref = a;";
3937 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3938 hasType(blockPointerType()))));
3939 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3940 hasType(memberPointerType()))));
3941 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3942 hasType(pointerType()))));
3943 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3944 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003945 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3946 hasType(lValueReferenceType()))));
3947 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3948 hasType(rValueReferenceType()))));
3949
3950 Fragment = "int &&ref = 2;";
3951 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3952 hasType(blockPointerType()))));
3953 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3954 hasType(memberPointerType()))));
3955 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3956 hasType(pointerType()))));
3957 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3958 hasType(referenceType()))));
3959 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3960 hasType(lValueReferenceType()))));
3961 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3962 hasType(rValueReferenceType()))));
3963}
3964
3965TEST(TypeMatching, AutoRefTypes) {
3966 std::string Fragment = "auto a = 1;"
3967 "auto b = a;"
3968 "auto &c = a;"
3969 "auto &&d = c;"
3970 "auto &&e = 2;";
3971 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
3972 hasType(referenceType()))));
3973 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
3974 hasType(referenceType()))));
3975 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3976 hasType(referenceType()))));
3977 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3978 hasType(lValueReferenceType()))));
3979 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
3980 hasType(rValueReferenceType()))));
3981 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3982 hasType(referenceType()))));
3983 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3984 hasType(lValueReferenceType()))));
3985 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
3986 hasType(rValueReferenceType()))));
3987 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3988 hasType(referenceType()))));
3989 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
3990 hasType(lValueReferenceType()))));
3991 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3992 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003993}
3994
3995TEST(TypeMatching, PointeeTypes) {
3996 EXPECT_TRUE(matches("int b; int &a = b;",
3997 referenceType(pointee(builtinType()))));
3998 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
3999
4000 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004001 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004002
4003 EXPECT_TRUE(matches(
4004 "int const *A;",
4005 pointerType(pointee(isConstQualified(), builtinType()))));
4006 EXPECT_TRUE(notMatches(
4007 "int *A;",
4008 pointerType(pointee(isConstQualified(), builtinType()))));
4009}
4010
4011TEST(TypeMatching, MatchesPointersToConstTypes) {
4012 EXPECT_TRUE(matches("int b; int * const a = &b;",
4013 loc(pointerType())));
4014 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004015 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004016 EXPECT_TRUE(matches(
4017 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004018 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004019 EXPECT_TRUE(matches(
4020 "int b; const int * a = &b;",
4021 pointerType(pointee(builtinType()))));
4022}
4023
4024TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004025 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4026 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004027}
4028
Edwin Vanef901b712013-02-25 14:49:29 +00004029TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004030 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004031 templateSpecializationType()));
4032}
4033
Edwin Vaneb6eae142013-02-25 20:43:32 +00004034TEST(TypeMatching, MatchesRecordType) {
4035 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004036 EXPECT_TRUE(matches("struct S{}; S s;",
4037 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4038 EXPECT_TRUE(notMatches("int i;",
4039 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004040}
4041
4042TEST(TypeMatching, MatchesElaboratedType) {
4043 EXPECT_TRUE(matches(
4044 "namespace N {"
4045 " namespace M {"
4046 " class D {};"
4047 " }"
4048 "}"
4049 "N::M::D d;", elaboratedType()));
4050 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4051 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4052}
4053
4054TEST(ElaboratedTypeNarrowing, hasQualifier) {
4055 EXPECT_TRUE(matches(
4056 "namespace N {"
4057 " namespace M {"
4058 " class D {};"
4059 " }"
4060 "}"
4061 "N::M::D d;",
4062 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4063 EXPECT_TRUE(notMatches(
4064 "namespace M {"
4065 " class D {};"
4066 "}"
4067 "M::D d;",
4068 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004069 EXPECT_TRUE(notMatches(
4070 "struct D {"
4071 "} d;",
4072 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004073}
4074
4075TEST(ElaboratedTypeNarrowing, namesType) {
4076 EXPECT_TRUE(matches(
4077 "namespace N {"
4078 " namespace M {"
4079 " class D {};"
4080 " }"
4081 "}"
4082 "N::M::D d;",
4083 elaboratedType(elaboratedType(namesType(recordType(
4084 hasDeclaration(namedDecl(hasName("D")))))))));
4085 EXPECT_TRUE(notMatches(
4086 "namespace M {"
4087 " class D {};"
4088 "}"
4089 "M::D d;",
4090 elaboratedType(elaboratedType(namesType(typedefType())))));
4091}
4092
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004093TEST(NNS, MatchesNestedNameSpecifiers) {
4094 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4095 nestedNameSpecifier()));
4096 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4097 nestedNameSpecifier()));
4098 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4099 nestedNameSpecifier()));
4100
4101 EXPECT_TRUE(matches(
4102 "struct A { static void f() {} }; void g() { A::f(); }",
4103 nestedNameSpecifier()));
4104 EXPECT_TRUE(notMatches(
4105 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4106 nestedNameSpecifier()));
4107}
4108
Daniel Jasper87c3d362012-09-20 14:12:57 +00004109TEST(NullStatement, SimpleCases) {
4110 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4111 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4112}
4113
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004114TEST(NNS, MatchesTypes) {
4115 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4116 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4117 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4118 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4119 Matcher));
4120 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4121}
4122
4123TEST(NNS, MatchesNamespaceDecls) {
4124 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4125 specifiesNamespace(hasName("ns")));
4126 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4127 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4128 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4129}
4130
4131TEST(NNS, BindsNestedNameSpecifiers) {
4132 EXPECT_TRUE(matchAndVerifyResultTrue(
4133 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4134 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4135 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4136}
4137
4138TEST(NNS, BindsNestedNameSpecifierLocs) {
4139 EXPECT_TRUE(matchAndVerifyResultTrue(
4140 "namespace ns { struct B {}; } ns::B b;",
4141 loc(nestedNameSpecifier()).bind("loc"),
4142 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4143}
4144
4145TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4146 EXPECT_TRUE(matches(
4147 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4148 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4149 EXPECT_TRUE(matches(
4150 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004151 nestedNameSpecifierLoc(hasPrefix(
4152 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004153}
4154
Daniel Jasper6fc34332012-10-30 15:42:00 +00004155TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4156 std::string Fragment =
4157 "namespace a { struct A { struct B { struct C {}; }; }; };"
4158 "void f() { a::A::B::C c; }";
4159 EXPECT_TRUE(matches(
4160 Fragment,
4161 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4162 hasDescendant(nestedNameSpecifier(
4163 specifiesNamespace(hasName("a")))))));
4164 EXPECT_TRUE(notMatches(
4165 Fragment,
4166 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4167 has(nestedNameSpecifier(
4168 specifiesNamespace(hasName("a")))))));
4169 EXPECT_TRUE(matches(
4170 Fragment,
4171 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4172 has(nestedNameSpecifier(
4173 specifiesNamespace(hasName("a")))))));
4174
4175 // Not really useful because a NestedNameSpecifier can af at most one child,
4176 // but to complete the interface.
4177 EXPECT_TRUE(matchAndVerifyResultTrue(
4178 Fragment,
4179 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4180 forEach(nestedNameSpecifier().bind("x"))),
4181 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4182}
4183
4184TEST(NNS, NestedNameSpecifiersAsDescendants) {
4185 std::string Fragment =
4186 "namespace a { struct A { struct B { struct C {}; }; }; };"
4187 "void f() { a::A::B::C c; }";
4188 EXPECT_TRUE(matches(
4189 Fragment,
4190 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4191 asString("struct a::A")))))));
4192 EXPECT_TRUE(matchAndVerifyResultTrue(
4193 Fragment,
4194 functionDecl(hasName("f"),
4195 forEachDescendant(nestedNameSpecifier().bind("x"))),
4196 // Nested names: a, a::A and a::A::B.
4197 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4198}
4199
4200TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4201 std::string Fragment =
4202 "namespace a { struct A { struct B { struct C {}; }; }; };"
4203 "void f() { a::A::B::C c; }";
4204 EXPECT_TRUE(matches(
4205 Fragment,
4206 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4207 hasDescendant(loc(nestedNameSpecifier(
4208 specifiesNamespace(hasName("a"))))))));
4209 EXPECT_TRUE(notMatches(
4210 Fragment,
4211 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4212 has(loc(nestedNameSpecifier(
4213 specifiesNamespace(hasName("a"))))))));
4214 EXPECT_TRUE(matches(
4215 Fragment,
4216 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4217 has(loc(nestedNameSpecifier(
4218 specifiesNamespace(hasName("a"))))))));
4219
4220 EXPECT_TRUE(matchAndVerifyResultTrue(
4221 Fragment,
4222 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4223 forEach(nestedNameSpecifierLoc().bind("x"))),
4224 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4225}
4226
4227TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4228 std::string Fragment =
4229 "namespace a { struct A { struct B { struct C {}; }; }; };"
4230 "void f() { a::A::B::C c; }";
4231 EXPECT_TRUE(matches(
4232 Fragment,
4233 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4234 asString("struct a::A"))))))));
4235 EXPECT_TRUE(matchAndVerifyResultTrue(
4236 Fragment,
4237 functionDecl(hasName("f"),
4238 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4239 // Nested names: a, a::A and a::A::B.
4240 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4241}
4242
Manuel Klimek191c0932013-02-01 13:41:35 +00004243template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004244public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004245 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4246 StringRef InnerId)
4247 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004248 }
4249
Manuel Klimek191c0932013-02-01 13:41:35 +00004250 virtual bool run(const BoundNodes *Nodes) { return false; }
4251
Manuel Klimekc2687452012-10-24 14:47:44 +00004252 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4253 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004254 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4255 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004256 }
4257private:
4258 std::string Id;
4259 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004260 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004261};
4262
4263TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004264 EXPECT_TRUE(matchAndVerifyResultTrue(
4265 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4266 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004267 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4268 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004269 EXPECT_TRUE(matchAndVerifyResultFalse(
4270 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4271 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004272 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4273 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004274}
4275
4276TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004277 EXPECT_TRUE(matchAndVerifyResultTrue(
4278 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004279 new VerifyMatchOnNode<clang::Stmt>(
4280 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004281 EXPECT_TRUE(matchAndVerifyResultFalse(
4282 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004283 new VerifyMatchOnNode<clang::Stmt>(
4284 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004285}
4286
4287TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4288 EXPECT_TRUE(matchAndVerifyResultTrue(
4289 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4290 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004291 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004292 EXPECT_TRUE(matchAndVerifyResultFalse(
4293 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4294 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004295 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004296}
4297
Manuel Klimekbee08572013-02-07 12:42:10 +00004298template <typename T>
4299class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4300public:
4301 virtual bool run(const BoundNodes *Nodes) { return false; }
4302
4303 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4304 const T *Node = Nodes->getNodeAs<T>("");
4305 return verify(*Nodes, *Context, Node);
4306 }
4307
4308 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004309 // Use the original typed pointer to verify we can pass pointers to subtypes
4310 // to equalsNode.
4311 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004312 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004313 "", match(stmt(hasParent(
4314 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004315 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004316 }
4317 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004318 // Use the original typed pointer to verify we can pass pointers to subtypes
4319 // to equalsNode.
4320 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004321 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004322 "", match(decl(hasParent(
4323 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004324 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004325 }
4326};
4327
4328TEST(IsEqualTo, MatchesNodesByIdentity) {
4329 EXPECT_TRUE(matchAndVerifyResultTrue(
4330 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004331 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4332 EXPECT_TRUE(matchAndVerifyResultTrue(
4333 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4334 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004335}
4336
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004337class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4338public:
4339 VerifyStartOfTranslationUnit() : Called(false) {}
4340 virtual void run(const MatchFinder::MatchResult &Result) {
4341 EXPECT_TRUE(Called);
4342 }
4343 virtual void onStartOfTranslationUnit() {
4344 Called = true;
4345 }
4346 bool Called;
4347};
4348
4349TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4350 MatchFinder Finder;
4351 VerifyStartOfTranslationUnit VerifyCallback;
4352 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004353 std::unique_ptr<FrontendActionFactory> Factory(
4354 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004355 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4356 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004357
4358 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004359 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004360 ASSERT_TRUE(AST.get());
4361 Finder.matchAST(AST->getASTContext());
4362 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004363}
4364
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004365class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4366public:
4367 VerifyEndOfTranslationUnit() : Called(false) {}
4368 virtual void run(const MatchFinder::MatchResult &Result) {
4369 EXPECT_FALSE(Called);
4370 }
4371 virtual void onEndOfTranslationUnit() {
4372 Called = true;
4373 }
4374 bool Called;
4375};
4376
4377TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4378 MatchFinder Finder;
4379 VerifyEndOfTranslationUnit VerifyCallback;
4380 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004381 std::unique_ptr<FrontendActionFactory> Factory(
4382 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004383 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4384 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004385
4386 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004387 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004388 ASSERT_TRUE(AST.get());
4389 Finder.matchAST(AST->getASTContext());
4390 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004391}
4392
Manuel Klimekbbb75852013-06-20 14:06:32 +00004393TEST(EqualsBoundNodeMatcher, QualType) {
4394 EXPECT_TRUE(matches(
4395 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4396 hasInitializer(ignoringParenImpCasts(
4397 hasType(qualType(equalsBoundNode("type"))))))));
4398 EXPECT_TRUE(notMatches("int i = 1.f;",
4399 varDecl(hasType(qualType().bind("type")),
4400 hasInitializer(ignoringParenImpCasts(hasType(
4401 qualType(equalsBoundNode("type"))))))));
4402}
4403
4404TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4405 EXPECT_TRUE(notMatches(
4406 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4407 hasInitializer(ignoringParenImpCasts(
4408 hasType(qualType(equalsBoundNode("type"))))))));
4409}
4410
4411TEST(EqualsBoundNodeMatcher, Stmt) {
4412 EXPECT_TRUE(
4413 matches("void f() { if(true) {} }",
4414 stmt(allOf(ifStmt().bind("if"),
4415 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4416
4417 EXPECT_TRUE(notMatches(
4418 "void f() { if(true) { if (true) {} } }",
4419 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4420}
4421
4422TEST(EqualsBoundNodeMatcher, Decl) {
4423 EXPECT_TRUE(matches(
4424 "class X { class Y {}; };",
4425 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4426 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4427
4428 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4429 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4430 has(decl(equalsBoundNode("record")))))));
4431}
4432
4433TEST(EqualsBoundNodeMatcher, Type) {
4434 EXPECT_TRUE(matches(
4435 "class X { int a; int b; };",
4436 recordDecl(
4437 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4438 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4439
4440 EXPECT_TRUE(notMatches(
4441 "class X { int a; double b; };",
4442 recordDecl(
4443 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4444 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4445}
4446
4447TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004448 EXPECT_TRUE(matchAndVerifyResultTrue(
4449 "int f() {"
4450 " if (1) {"
4451 " int i = 9;"
4452 " }"
4453 " int j = 10;"
4454 " {"
4455 " float k = 9.0;"
4456 " }"
4457 " return 0;"
4458 "}",
4459 // Look for variable declarations within functions whose type is the same
4460 // as the function return type.
4461 functionDecl(returns(qualType().bind("type")),
4462 forEachDescendant(varDecl(hasType(
4463 qualType(equalsBoundNode("type")))).bind("decl"))),
4464 // Only i and j should match, not k.
4465 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4466}
4467
4468TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4469 EXPECT_TRUE(matchAndVerifyResultTrue(
4470 "void f() {"
4471 " int x;"
4472 " double d;"
4473 " x = d + x - d + x;"
4474 "}",
4475 functionDecl(
4476 hasName("f"), forEachDescendant(varDecl().bind("d")),
4477 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4478 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4479}
4480
Manuel Klimekce68f772014-03-25 14:39:26 +00004481TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4482 EXPECT_TRUE(matchAndVerifyResultTrue(
4483 "struct StringRef { int size() const; const char* data() const; };"
4484 "void f(StringRef v) {"
4485 " v.data();"
4486 "}",
4487 memberCallExpr(
4488 callee(methodDecl(hasName("data"))),
4489 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4490 .bind("var")))),
4491 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4492 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4493 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4494 .bind("data"),
4495 new VerifyIdIsBoundTo<Expr>("data", 1)));
4496
4497 EXPECT_FALSE(matches(
4498 "struct StringRef { int size() const; const char* data() const; };"
4499 "void f(StringRef v) {"
4500 " v.data();"
4501 " v.size();"
4502 "}",
4503 memberCallExpr(
4504 callee(methodDecl(hasName("data"))),
4505 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4506 .bind("var")))),
4507 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4508 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4509 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4510 .bind("data")));
4511}
4512
Manuel Klimek04616e42012-07-06 05:48:52 +00004513} // end namespace ast_matchers
4514} // end namespace clang