blob: 7a639aac81caa3ef59454d90b9547facf1e54cfd [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 Klimekd52a3b82014-08-05 09:45:53 +0000652TEST(DeclarationMatcher, MatchCudaDecl) {
653 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
654 "void g() { f<<<1, 2>>>(); }",
655 CUDAKernelCallExpr()));
656 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
657 hasCudaDeviceAttr()));
658 EXPECT_TRUE(matchesWithCuda("__attribute__((host)) void f() {}",
659 hasCudaHostAttr()));
660 EXPECT_TRUE(matchesWithCuda("__attribute__((global)) void f() {}",
661 hasCudaGlobalAttr()));
662 EXPECT_FALSE(matchesWithCuda("void f() {}",
663 hasCudaGlobalAttr()));
664 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
665 hasCudaGlobalAttr()));
666 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
667 hasCudaGlobalAttr()));
668}
669
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000670// Implements a run method that returns whether BoundNodes contains a
671// Decl bound to Id that can be dynamically cast to T.
672// Optionally checks that the check succeeded a specific number of times.
673template <typename T>
674class VerifyIdIsBoundTo : public BoundNodesCallback {
675public:
676 // Create an object that checks that a node of type \c T was bound to \c Id.
677 // Does not check for a certain number of matches.
678 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
679 : Id(Id), ExpectedCount(-1), Count(0) {}
680
681 // Create an object that checks that a node of type \c T was bound to \c Id.
682 // Checks that there were exactly \c ExpectedCount matches.
683 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
684 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
685
686 // Create an object that checks that a node of type \c T was bound to \c Id.
687 // Checks that there was exactly one match with the name \c ExpectedName.
688 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000689 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
690 int ExpectedCount = 1)
691 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
692 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000693
Craig Toppera798a9d2014-03-02 09:32:10 +0000694 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000695 if (ExpectedCount != -1)
696 EXPECT_EQ(ExpectedCount, Count);
697 if (!ExpectedName.empty())
698 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000699 Count = 0;
700 Name.clear();
701 }
702
703 ~VerifyIdIsBoundTo() {
704 EXPECT_EQ(0, Count);
705 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000706 }
707
708 virtual bool run(const BoundNodes *Nodes) {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000709 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000710 if (Nodes->getNodeAs<T>(Id)) {
711 ++Count;
712 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
713 Name = Named->getNameAsString();
714 } else if (const NestedNameSpecifier *NNS =
715 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
716 llvm::raw_string_ostream OS(Name);
717 NNS->print(OS, PrintingPolicy(LangOptions()));
718 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000719 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
720 EXPECT_NE(M.end(), I);
721 if (I != M.end())
722 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000723 return true;
724 }
Craig Topper416fa342014-06-08 08:38:12 +0000725 EXPECT_TRUE(M.count(Id) == 0 ||
726 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000727 return false;
728 }
729
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000730 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
731 return run(Nodes);
732 }
733
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000734private:
735 const std::string Id;
736 const int ExpectedCount;
737 int Count;
738 const std::string ExpectedName;
739 std::string Name;
740};
741
742TEST(HasDescendant, MatchesDescendantTypes) {
743 EXPECT_TRUE(matches("void f() { int i = 3; }",
744 decl(hasDescendant(loc(builtinType())))));
745 EXPECT_TRUE(matches("void f() { int i = 3; }",
746 stmt(hasDescendant(builtinType()))));
747
748 EXPECT_TRUE(matches("void f() { int i = 3; }",
749 stmt(hasDescendant(loc(builtinType())))));
750 EXPECT_TRUE(matches("void f() { int i = 3; }",
751 stmt(hasDescendant(qualType(builtinType())))));
752
753 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
754 stmt(hasDescendant(isInteger()))));
755
756 EXPECT_TRUE(matchAndVerifyResultTrue(
757 "void f() { int a; float c; int d; int e; }",
758 functionDecl(forEachDescendant(
759 varDecl(hasDescendant(isInteger())).bind("x"))),
760 new VerifyIdIsBoundTo<Decl>("x", 3)));
761}
762
763TEST(HasDescendant, MatchesDescendantsOfTypes) {
764 EXPECT_TRUE(matches("void f() { int*** i; }",
765 qualType(hasDescendant(builtinType()))));
766 EXPECT_TRUE(matches("void f() { int*** i; }",
767 qualType(hasDescendant(
768 pointerType(pointee(builtinType()))))));
769 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000770 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000771
772 EXPECT_TRUE(matchAndVerifyResultTrue(
773 "void f() { int*** i; }",
774 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
775 new VerifyIdIsBoundTo<Type>("x", 2)));
776}
777
778TEST(Has, MatchesChildrenOfTypes) {
779 EXPECT_TRUE(matches("int i;",
780 varDecl(hasName("i"), has(isInteger()))));
781 EXPECT_TRUE(notMatches("int** i;",
782 varDecl(hasName("i"), has(isInteger()))));
783 EXPECT_TRUE(matchAndVerifyResultTrue(
784 "int (*f)(float, int);",
785 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
786 new VerifyIdIsBoundTo<QualType>("x", 2)));
787}
788
789TEST(Has, MatchesChildTypes) {
790 EXPECT_TRUE(matches(
791 "int* i;",
792 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
793 EXPECT_TRUE(notMatches(
794 "int* i;",
795 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
796}
797
Daniel Jasper1dad1832012-07-10 20:20:19 +0000798TEST(Enum, DoesNotMatchClasses) {
799 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
800}
801
802TEST(Enum, MatchesEnums) {
803 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
804}
805
806TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000807 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000808 EXPECT_TRUE(matches("enum X{ A };", Matcher));
809 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
810 EXPECT_TRUE(notMatches("enum X {};", Matcher));
811}
812
Manuel Klimek04616e42012-07-06 05:48:52 +0000813TEST(StatementMatcher, Has) {
814 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000815 expr(hasType(pointsTo(recordDecl(hasName("X")))),
816 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000817
818 EXPECT_TRUE(matches(
819 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
820 EXPECT_TRUE(notMatches(
821 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
822}
823
824TEST(StatementMatcher, HasDescendant) {
825 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000826 expr(hasType(pointsTo(recordDecl(hasName("X")))),
827 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000828
829 EXPECT_TRUE(matches(
830 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
831 HasDescendantVariableI));
832 EXPECT_TRUE(notMatches(
833 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
834 HasDescendantVariableI));
835}
836
837TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000838 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000839
840 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
841 EXPECT_TRUE(notMatches("class A {};", TypeA));
842
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000843 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000844
845 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
846 TypeDerivedFromA));
847 EXPECT_TRUE(notMatches("class A {};", TypeA));
848
849 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000850 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000851
852 EXPECT_TRUE(
853 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
854}
855
Manuel Klimek04616e42012-07-06 05:48:52 +0000856TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000857 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000858
859 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000860 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000861
862 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000863 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000864
865 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000866 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000867
868 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
869 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000870 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000871
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000872 StatementMatcher MethodX =
873 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000874
875 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
876 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000877 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000878}
879
880TEST(Matcher, BindTheSameNameInAlternatives) {
881 StatementMatcher matcher = anyOf(
882 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000883 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000884 hasRHS(integerLiteral(equals(0)))),
885 binaryOperator(hasOperatorName("+"),
886 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000887 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000888
889 EXPECT_TRUE(matchAndVerifyResultTrue(
890 // The first branch of the matcher binds x to 0 but then fails.
891 // The second branch binds x to f() and succeeds.
892 "int f() { return 0 + f(); }",
893 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000894 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000895}
896
Manuel Klimekfdf98762012-08-30 19:41:06 +0000897TEST(Matcher, BindsIDForMemoizedResults) {
898 // Using the same matcher in two match expressions will make memoization
899 // kick in.
900 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
901 EXPECT_TRUE(matchAndVerifyResultTrue(
902 "class A { class B { class X {}; }; };",
903 DeclarationMatcher(anyOf(
904 recordDecl(hasName("A"), hasDescendant(ClassX)),
905 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000906 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000907}
908
Daniel Jasper856194d02012-12-03 15:43:25 +0000909TEST(HasDeclaration, HasDeclarationOfEnumType) {
910 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
911 expr(hasType(pointsTo(
912 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
913}
914
Edwin Vaneed936452013-02-25 14:32:42 +0000915TEST(HasDeclaration, HasGetDeclTraitTest) {
916 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
917 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
918 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
919}
920
Edwin Vane2c197e02013-02-19 17:14:34 +0000921TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
922 EXPECT_TRUE(matches("typedef int X; X a;",
923 varDecl(hasName("a"),
924 hasType(typedefType(hasDeclaration(decl()))))));
925
926 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
927}
928
Edwin Vanef901b712013-02-25 14:49:29 +0000929TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
930 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
931 varDecl(hasType(templateSpecializationType(
932 hasDeclaration(namedDecl(hasName("A"))))))));
933}
934
Manuel Klimek04616e42012-07-06 05:48:52 +0000935TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000936 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000937 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000938 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000939 EXPECT_TRUE(
940 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000941 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000942 EXPECT_TRUE(
943 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000944 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000945}
946
947TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000948 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000949 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000950 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000951 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000952 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000953 EXPECT_TRUE(
954 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000955 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000956}
957
958TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000959 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000960 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000961 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000962 EXPECT_TRUE(
963 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000964 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000965}
966
967TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000968 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000969 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000970 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000971 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000972 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000973}
974
Manuel Klimekc16c6522013-06-20 13:08:29 +0000975TEST(HasTypeLoc, MatchesDeclaratorDecls) {
976 EXPECT_TRUE(matches("int x;",
977 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
978
979 // Make sure we don't crash on implicit constructors.
980 EXPECT_TRUE(notMatches("class X {}; X x;",
981 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
982}
983
Manuel Klimek04616e42012-07-06 05:48:52 +0000984TEST(Matcher, Call) {
985 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +0000986 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000987 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000988
989 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
990 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
991
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000992 StatementMatcher MethodOnY =
993 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000994
995 EXPECT_TRUE(
996 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
997 MethodOnY));
998 EXPECT_TRUE(
999 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1000 MethodOnY));
1001 EXPECT_TRUE(
1002 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1003 MethodOnY));
1004 EXPECT_TRUE(
1005 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1006 MethodOnY));
1007 EXPECT_TRUE(
1008 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1009 MethodOnY));
1010
1011 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001012 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001013
1014 EXPECT_TRUE(
1015 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1016 MethodOnYPointer));
1017 EXPECT_TRUE(
1018 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1019 MethodOnYPointer));
1020 EXPECT_TRUE(
1021 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1022 MethodOnYPointer));
1023 EXPECT_TRUE(
1024 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1025 MethodOnYPointer));
1026 EXPECT_TRUE(
1027 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1028 MethodOnYPointer));
1029}
1030
Daniel Jasper5901e472012-10-01 13:40:41 +00001031TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001032 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001033 lambdaExpr()));
1034}
1035
1036TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001037 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1038 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001039 forRangeStmt()));
1040 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1041 forRangeStmt()));
1042}
1043
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001044TEST(Matcher, SubstNonTypeTemplateParm) {
1045 EXPECT_FALSE(matches("template<int N>\n"
1046 "struct A { static const int n = 0; };\n"
1047 "struct B : public A<42> {};",
1048 substNonTypeTemplateParmExpr()));
1049 EXPECT_TRUE(matches("template<int N>\n"
1050 "struct A { static const int n = N; };\n"
1051 "struct B : public A<42> {};",
1052 substNonTypeTemplateParmExpr()));
1053}
1054
Daniel Jasper5901e472012-10-01 13:40:41 +00001055TEST(Matcher, UserDefinedLiteral) {
1056 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1057 " return i + 1;"
1058 "}"
1059 "char c = 'a'_inc;",
1060 userDefinedLiteral()));
1061}
1062
Daniel Jasper87c3d362012-09-20 14:12:57 +00001063TEST(Matcher, FlowControl) {
1064 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1065 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1066 continueStmt()));
1067 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1068 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1069 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1070}
1071
Daniel Jasper1dad1832012-07-10 20:20:19 +00001072TEST(HasType, MatchesAsString) {
1073 EXPECT_TRUE(
1074 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001075 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001076 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001077 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001078 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001079 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001080 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001081 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001082}
1083
Manuel Klimek04616e42012-07-06 05:48:52 +00001084TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001085 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001086 // Unary operator
1087 EXPECT_TRUE(matches("class Y { }; "
1088 "bool operator!(Y x) { return false; }; "
1089 "Y y; bool c = !y;", OpCall));
1090 // No match -- special operators like "new", "delete"
1091 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1092 // we need to figure out include paths in the test.
1093 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1094 // "class Y { }; "
1095 // "void *operator new(size_t size) { return 0; } "
1096 // "Y *y = new Y;", OpCall));
1097 EXPECT_TRUE(notMatches("class Y { }; "
1098 "void operator delete(void *p) { } "
1099 "void a() {Y *y = new Y; delete y;}", OpCall));
1100 // Binary operator
1101 EXPECT_TRUE(matches("class Y { }; "
1102 "bool operator&&(Y x, Y y) { return true; }; "
1103 "Y a; Y b; bool c = a && b;",
1104 OpCall));
1105 // No match -- normal operator, not an overloaded one.
1106 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1107 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1108}
1109
1110TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1111 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001112 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001113 EXPECT_TRUE(matches("class Y { }; "
1114 "bool operator&&(Y x, Y y) { return true; }; "
1115 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1116 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001117 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001118 EXPECT_TRUE(notMatches("class Y { }; "
1119 "bool operator&&(Y x, Y y) { return true; }; "
1120 "Y a; Y b; bool c = a && b;",
1121 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001122 StatementMatcher OpStarCall =
1123 operatorCallExpr(hasOverloadedOperatorName("*"));
1124 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1125 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001126 DeclarationMatcher ClassWithOpStar =
1127 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1128 EXPECT_TRUE(matches("class Y { int operator*(); };",
1129 ClassWithOpStar));
1130 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1131 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001132 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1133 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1134 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001135}
1136
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001137TEST(Matcher, NestedOverloadedOperatorCalls) {
1138 EXPECT_TRUE(matchAndVerifyResultTrue(
1139 "class Y { }; "
1140 "Y& operator&&(Y& x, Y& y) { return x; }; "
1141 "Y a; Y b; Y c; Y d = a && b && c;",
1142 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1143 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1144 EXPECT_TRUE(matches(
1145 "class Y { }; "
1146 "Y& operator&&(Y& x, Y& y) { return x; }; "
1147 "Y a; Y b; Y c; Y d = a && b && c;",
1148 operatorCallExpr(hasParent(operatorCallExpr()))));
1149 EXPECT_TRUE(matches(
1150 "class Y { }; "
1151 "Y& operator&&(Y& x, Y& y) { return x; }; "
1152 "Y a; Y b; Y c; Y d = a && b && c;",
1153 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1154}
1155
Manuel Klimek04616e42012-07-06 05:48:52 +00001156TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001157 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001158 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001159
1160 EXPECT_TRUE(
1161 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1162 MethodOnY));
1163 EXPECT_TRUE(
1164 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1165 MethodOnY));
1166 EXPECT_TRUE(
1167 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1168 MethodOnY));
1169 EXPECT_TRUE(
1170 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1171 MethodOnY));
1172 EXPECT_TRUE(
1173 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1174 MethodOnY));
1175
1176 EXPECT_TRUE(matches(
1177 "class Y {"
1178 " public: virtual void x();"
1179 "};"
1180 "class X : public Y {"
1181 " public: virtual void x();"
1182 "};"
1183 "void z() { X *x; x->Y::x(); }", MethodOnY));
1184}
1185
1186TEST(Matcher, VariableUsage) {
1187 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001188 declRefExpr(to(
1189 varDecl(hasInitializer(
1190 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001191
1192 EXPECT_TRUE(matches(
1193 "class Y {"
1194 " public:"
1195 " bool x() const;"
1196 "};"
1197 "void z(const Y &y) {"
1198 " bool b = y.x();"
1199 " if (b) {}"
1200 "}", Reference));
1201
1202 EXPECT_TRUE(notMatches(
1203 "class Y {"
1204 " public:"
1205 " bool x() const;"
1206 "};"
1207 "void z(const Y &y) {"
1208 " bool b = y.x();"
1209 "}", Reference));
1210}
1211
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001212TEST(Matcher, VarDecl_Storage) {
1213 auto M = varDecl(hasName("X"), hasLocalStorage());
1214 EXPECT_TRUE(matches("void f() { int X; }", M));
1215 EXPECT_TRUE(notMatches("int X;", M));
1216 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1217
1218 M = varDecl(hasName("X"), hasGlobalStorage());
1219 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1220 EXPECT_TRUE(matches("int X;", M));
1221 EXPECT_TRUE(matches("void f() { static int X; }", M));
1222}
1223
Manuel Klimek61379422012-12-04 14:42:08 +00001224TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001225 EXPECT_TRUE(matches(
1226 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001227 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001228}
1229
Manuel Klimek04616e42012-07-06 05:48:52 +00001230TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001231 StatementMatcher CallOnVariableY =
1232 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001233
1234 EXPECT_TRUE(matches(
1235 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1236 EXPECT_TRUE(matches(
1237 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1238 EXPECT_TRUE(matches(
1239 "class Y { public: void x(); };"
1240 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1241 EXPECT_TRUE(matches(
1242 "class Y { public: void x(); };"
1243 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1244 EXPECT_TRUE(notMatches(
1245 "class Y { public: void x(); };"
1246 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1247 CallOnVariableY));
1248}
1249
Daniel Jasper1dad1832012-07-10 20:20:19 +00001250TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1251 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1252 unaryExprOrTypeTraitExpr()));
1253 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1254 alignOfExpr(anything())));
1255 // FIXME: Uncomment once alignof is enabled.
1256 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1257 // unaryExprOrTypeTraitExpr()));
1258 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1259 // sizeOfExpr()));
1260}
1261
1262TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1263 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1264 hasArgumentOfType(asString("int")))));
1265 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1266 hasArgumentOfType(asString("float")))));
1267 EXPECT_TRUE(matches(
1268 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001269 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001270 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001271 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001272}
1273
Manuel Klimek04616e42012-07-06 05:48:52 +00001274TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001275 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001276}
1277
1278TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001279 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001280}
1281
1282TEST(MemberExpression, MatchesVariable) {
1283 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001284 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001285 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001286 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001287 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001288 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001289}
1290
1291TEST(MemberExpression, MatchesStaticVariable) {
1292 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001293 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001294 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001295 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001296 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001297 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001298}
1299
Daniel Jasper4e566c42012-07-12 08:50:38 +00001300TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001301 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1302 EXPECT_TRUE(matches(
1303 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1304 callExpr(hasArgument(0, declRefExpr(
1305 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001306}
1307
1308TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001309 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001310 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001311 callExpr(hasArgument(0, declRefExpr(
1312 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001313}
1314
Manuel Klimek04616e42012-07-06 05:48:52 +00001315TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1316 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001317 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001318 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001319 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001320 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001321 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001322}
1323
1324TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1325 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001326 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001327 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001328 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001329 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001330 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001331}
1332
1333TEST(IsArrow, MatchesMemberCallsViaArrow) {
1334 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001335 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001336 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001337 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001338 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001339 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001340}
1341
1342TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001343 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001344
1345 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1346 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1347}
1348
1349TEST(Callee, MatchesMemberExpressions) {
1350 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001351 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001352 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001353 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001354}
1355
1356TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001357 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001358
1359 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1360 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1361
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001362 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1363 llvm::Triple::Win32) {
1364 // FIXME: Make this work for MSVC.
1365 // Dependent contexts, but a non-dependent call.
1366 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1367 CallFunctionF));
1368 EXPECT_TRUE(
1369 matches("void f(); template <int N> struct S { void g() { f(); } };",
1370 CallFunctionF));
1371 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001372
1373 // Depedent calls don't match.
1374 EXPECT_TRUE(
1375 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1376 CallFunctionF));
1377 EXPECT_TRUE(
1378 notMatches("void f(int);"
1379 "template <typename T> struct S { void g(T t) { f(t); } };",
1380 CallFunctionF));
1381}
1382
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001383TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1384 EXPECT_TRUE(
1385 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001386 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001387}
1388
1389TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1390 EXPECT_TRUE(
1391 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001392 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001393}
1394
1395TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1396 EXPECT_TRUE(
1397 notMatches("void g(); template <typename T> void f(T t) {}"
1398 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001399 functionTemplateDecl(hasName("f"),
1400 hasDescendant(declRefExpr(to(
1401 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001402}
1403
Manuel Klimek04616e42012-07-06 05:48:52 +00001404TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001405 StatementMatcher CallArgumentY = callExpr(
1406 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001407
1408 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1409 EXPECT_TRUE(
1410 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1411 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1412
Daniel Jasper848cbe12012-09-18 13:09:13 +00001413 StatementMatcher WrongIndex = callExpr(
1414 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001415 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1416}
1417
1418TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001419 StatementMatcher CallArgumentY = callExpr(
1420 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001421 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1422 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1423 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1424}
1425
1426TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001427 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001428
1429 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1430 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1431 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1432}
1433
Daniel Jasper9f501292012-12-04 11:54:27 +00001434TEST(Matcher, ParameterCount) {
1435 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1436 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1437 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1438 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1439 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1440}
1441
Manuel Klimek04616e42012-07-06 05:48:52 +00001442TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001443 DeclarationMatcher ReferenceClassX = varDecl(
1444 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001445 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1446 ReferenceClassX));
1447 EXPECT_TRUE(
1448 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001449 // The match here is on the implicit copy constructor code for
1450 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001451 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001452 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1453 EXPECT_TRUE(
1454 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001455 EXPECT_TRUE(
1456 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1457}
1458
Edwin Vane0a4836e2013-03-06 17:02:57 +00001459TEST(QualType, hasCanonicalType) {
1460 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1461 "int a;"
1462 "int_ref b = a;",
1463 varDecl(hasType(qualType(referenceType())))));
1464 EXPECT_TRUE(
1465 matches("typedef int &int_ref;"
1466 "int a;"
1467 "int_ref b = a;",
1468 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1469}
1470
Edwin Vane119d3df2013-04-02 18:15:55 +00001471TEST(QualType, hasLocalQualifiers) {
1472 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1473 varDecl(hasType(hasLocalQualifiers()))));
1474 EXPECT_TRUE(matches("int *const j = nullptr;",
1475 varDecl(hasType(hasLocalQualifiers()))));
1476 EXPECT_TRUE(matches("int *volatile k;",
1477 varDecl(hasType(hasLocalQualifiers()))));
1478 EXPECT_TRUE(notMatches("int m;",
1479 varDecl(hasType(hasLocalQualifiers()))));
1480}
1481
Manuel Klimek04616e42012-07-06 05:48:52 +00001482TEST(HasParameter, CallsInnerMatcher) {
1483 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001484 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001485 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001486 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001487}
1488
1489TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1490 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001491 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001492}
1493
1494TEST(HasType, MatchesParameterVariableTypesStrictly) {
1495 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001496 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001497 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001498 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001499 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001500 methodDecl(hasParameter(0,
1501 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001502 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001503 methodDecl(hasParameter(0,
1504 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001505}
1506
1507TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1508 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001509 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001510 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001511 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001512}
1513
Daniel Jasper1dad1832012-07-10 20:20:19 +00001514TEST(Returns, MatchesReturnTypes) {
1515 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001516 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001517 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001518 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001519 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001520 functionDecl(returns(hasDeclaration(
1521 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001522}
1523
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001524TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001525 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1526 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1527 functionDecl(isExternC())));
1528 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001529}
1530
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001531TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1532 EXPECT_TRUE(
1533 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1534 EXPECT_TRUE(matches("void Func() = delete;",
1535 functionDecl(hasName("Func"), isDeleted())));
1536}
1537
Manuel Klimek04616e42012-07-06 05:48:52 +00001538TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1539 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001540 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001541}
1542
1543TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1544 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001545 methodDecl(hasAnyParameter(hasType(pointsTo(
1546 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001547}
1548
Alp Toker8db6e7a2014-01-05 06:38:57 +00001549TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001550 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001551 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001552 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001553 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001554}
1555
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001556TEST(Matcher, MatchesClassTemplateSpecialization) {
1557 EXPECT_TRUE(matches("template<typename T> struct A {};"
1558 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001559 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001560 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001561 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001562 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001563 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001564}
1565
Manuel Klimekc16c6522013-06-20 13:08:29 +00001566TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1567 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1568 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1569}
1570
1571TEST(ParmVarDecl, MatchesParmVars) {
1572 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1573 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1574}
1575
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001576TEST(Matcher, MatchesTypeTemplateArgument) {
1577 EXPECT_TRUE(matches(
1578 "template<typename T> struct B {};"
1579 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001580 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001581 asString("int"))))));
1582}
1583
1584TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1585 EXPECT_TRUE(matches(
1586 "struct B { int next; };"
1587 "template<int(B::*next_ptr)> struct A {};"
1588 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001589 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1590 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001591
1592 EXPECT_TRUE(notMatches(
1593 "template <typename T> struct A {};"
1594 "A<int> a;",
1595 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1596 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001597
1598 EXPECT_TRUE(matches(
1599 "struct B { int next; };"
1600 "template<int(B::*next_ptr)> struct A {};"
1601 "A<&B::next> a;",
1602 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1603 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1604
1605 EXPECT_TRUE(notMatches(
1606 "template <typename T> struct A {};"
1607 "A<int> a;",
1608 templateSpecializationType(hasAnyTemplateArgument(
1609 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001610}
1611
1612TEST(Matcher, MatchesSpecificArgument) {
1613 EXPECT_TRUE(matches(
1614 "template<typename T, typename U> class A {};"
1615 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001616 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001617 1, refersToType(asString("int"))))));
1618 EXPECT_TRUE(notMatches(
1619 "template<typename T, typename U> class A {};"
1620 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001621 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001622 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001623
1624 EXPECT_TRUE(matches(
1625 "template<typename T, typename U> class A {};"
1626 "A<bool, int> a;",
1627 templateSpecializationType(hasTemplateArgument(
1628 1, refersToType(asString("int"))))));
1629 EXPECT_TRUE(notMatches(
1630 "template<typename T, typename U> class A {};"
1631 "A<int, bool> a;",
1632 templateSpecializationType(hasTemplateArgument(
1633 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001634}
1635
Daniel Jasper639522c2013-02-25 12:02:08 +00001636TEST(Matcher, MatchesAccessSpecDecls) {
1637 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1638 EXPECT_TRUE(
1639 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1640 EXPECT_TRUE(
1641 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1642 EXPECT_TRUE(
1643 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1644
1645 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1646}
1647
Edwin Vane37ee1d72013-04-09 20:46:36 +00001648TEST(Matcher, MatchesVirtualMethod) {
1649 EXPECT_TRUE(matches("class X { virtual int f(); };",
1650 methodDecl(isVirtual(), hasName("::X::f"))));
1651 EXPECT_TRUE(notMatches("class X { int f(); };",
1652 methodDecl(isVirtual())));
1653}
1654
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001655TEST(Matcher, MatchesPureMethod) {
1656 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1657 methodDecl(isPure(), hasName("::X::f"))));
1658 EXPECT_TRUE(notMatches("class X { int f(); };",
1659 methodDecl(isPure())));
1660}
1661
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001662TEST(Matcher, MatchesConstMethod) {
1663 EXPECT_TRUE(matches("struct A { void foo() const; };",
1664 methodDecl(isConst())));
1665 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1666 methodDecl(isConst())));
1667}
1668
Edwin Vane37ee1d72013-04-09 20:46:36 +00001669TEST(Matcher, MatchesOverridingMethod) {
1670 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1671 "class Y : public X { int f(); };",
1672 methodDecl(isOverride(), hasName("::Y::f"))));
1673 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1674 "class Y : public X { int f(); };",
1675 methodDecl(isOverride(), hasName("::X::f"))));
1676 EXPECT_TRUE(notMatches("class X { int f(); }; "
1677 "class Y : public X { int f(); };",
1678 methodDecl(isOverride())));
1679 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1680 methodDecl(isOverride())));
1681}
1682
Manuel Klimek04616e42012-07-06 05:48:52 +00001683TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001684 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001685
1686 EXPECT_TRUE(
1687 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1688 EXPECT_TRUE(
1689 matches("class X { public: X(); }; void x() { X x = X(); }",
1690 Constructor));
1691 EXPECT_TRUE(
1692 matches("class X { public: X(int); }; void x() { X x = 0; }",
1693 Constructor));
1694 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1695}
1696
1697TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001698 StatementMatcher Constructor = constructExpr(
1699 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001700
1701 EXPECT_TRUE(
1702 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1703 Constructor));
1704 EXPECT_TRUE(
1705 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1706 Constructor));
1707 EXPECT_TRUE(
1708 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1709 Constructor));
1710 EXPECT_TRUE(
1711 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1712 Constructor));
1713
Daniel Jasper848cbe12012-09-18 13:09:13 +00001714 StatementMatcher WrongIndex = constructExpr(
1715 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001716 EXPECT_TRUE(
1717 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1718 WrongIndex));
1719}
1720
1721TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001722 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001723
1724 EXPECT_TRUE(
1725 matches("class X { public: X(int); }; void x() { X x(0); }",
1726 Constructor1Arg));
1727 EXPECT_TRUE(
1728 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1729 Constructor1Arg));
1730 EXPECT_TRUE(
1731 matches("class X { public: X(int); }; void x() { X x = 0; }",
1732 Constructor1Arg));
1733 EXPECT_TRUE(
1734 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1735 Constructor1Arg));
1736}
1737
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001738TEST(Matcher, ConstructorListInitialization) {
1739 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1740
1741 EXPECT_TRUE(
1742 matches("class X { public: X(int); }; void x() { X x{0}; }",
1743 ConstructorListInit));
1744 EXPECT_FALSE(
1745 matches("class X { public: X(int); }; void x() { X x(0); }",
1746 ConstructorListInit));
1747}
1748
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001749TEST(Matcher,ThisExpr) {
1750 EXPECT_TRUE(
1751 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1752 EXPECT_TRUE(
1753 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1754}
1755
Manuel Klimek04616e42012-07-06 05:48:52 +00001756TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001757 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001758
1759 std::string ClassString = "class string { public: string(); ~string(); }; ";
1760
1761 EXPECT_TRUE(
1762 matches(ClassString +
1763 "string GetStringByValue();"
1764 "void FunctionTakesString(string s);"
1765 "void run() { FunctionTakesString(GetStringByValue()); }",
1766 TempExpression));
1767
1768 EXPECT_TRUE(
1769 notMatches(ClassString +
1770 "string* GetStringPointer(); "
1771 "void FunctionTakesStringPtr(string* s);"
1772 "void run() {"
1773 " string* s = GetStringPointer();"
1774 " FunctionTakesStringPtr(GetStringPointer());"
1775 " FunctionTakesStringPtr(s);"
1776 "}",
1777 TempExpression));
1778
1779 EXPECT_TRUE(
1780 notMatches("class no_dtor {};"
1781 "no_dtor GetObjByValue();"
1782 "void ConsumeObj(no_dtor param);"
1783 "void run() { ConsumeObj(GetObjByValue()); }",
1784 TempExpression));
1785}
1786
Sam Panzer68a35af2012-08-24 22:04:44 +00001787TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1788 std::string ClassString =
1789 "class string { public: string(); int length(); }; ";
1790
1791 EXPECT_TRUE(
1792 matches(ClassString +
1793 "string GetStringByValue();"
1794 "void FunctionTakesString(string s);"
1795 "void run() { FunctionTakesString(GetStringByValue()); }",
1796 materializeTemporaryExpr()));
1797
1798 EXPECT_TRUE(
1799 notMatches(ClassString +
1800 "string* GetStringPointer(); "
1801 "void FunctionTakesStringPtr(string* s);"
1802 "void run() {"
1803 " string* s = GetStringPointer();"
1804 " FunctionTakesStringPtr(GetStringPointer());"
1805 " FunctionTakesStringPtr(s);"
1806 "}",
1807 materializeTemporaryExpr()));
1808
1809 EXPECT_TRUE(
1810 notMatches(ClassString +
1811 "string GetStringByValue();"
1812 "void run() { int k = GetStringByValue().length(); }",
1813 materializeTemporaryExpr()));
1814
1815 EXPECT_TRUE(
1816 notMatches(ClassString +
1817 "string GetStringByValue();"
1818 "void run() { GetStringByValue(); }",
1819 materializeTemporaryExpr()));
1820}
1821
Manuel Klimek04616e42012-07-06 05:48:52 +00001822TEST(ConstructorDeclaration, SimpleCase) {
1823 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001824 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001825 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001826 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001827}
1828
1829TEST(ConstructorDeclaration, IsImplicit) {
1830 // This one doesn't match because the constructor is not added by the
1831 // compiler (it is not needed).
1832 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001833 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001834 // The compiler added the implicit default constructor.
1835 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001836 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001837 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001838 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001839 // The compiler added an implicit assignment operator.
1840 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1841 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001842}
1843
Daniel Jasper1dad1832012-07-10 20:20:19 +00001844TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1845 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001846 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001847}
1848
1849TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001850 EXPECT_TRUE(notMatches("class Foo {};",
1851 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001852}
1853
Manuel Klimek04616e42012-07-06 05:48:52 +00001854TEST(HasAnyConstructorInitializer, SimpleCase) {
1855 EXPECT_TRUE(notMatches(
1856 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001857 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001858 EXPECT_TRUE(matches(
1859 "class Foo {"
1860 " Foo() : foo_() { }"
1861 " int foo_;"
1862 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001863 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001864}
1865
1866TEST(HasAnyConstructorInitializer, ForField) {
1867 static const char Code[] =
1868 "class Baz { };"
1869 "class Foo {"
1870 " Foo() : foo_() { }"
1871 " Baz foo_;"
1872 " Baz bar_;"
1873 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001874 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1875 forField(hasType(recordDecl(hasName("Baz"))))))));
1876 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001877 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001878 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1879 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001880}
1881
1882TEST(HasAnyConstructorInitializer, WithInitializer) {
1883 static const char Code[] =
1884 "class Foo {"
1885 " Foo() : foo_(0) { }"
1886 " int foo_;"
1887 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001888 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001889 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001890 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001891 withInitializer(integerLiteral(equals(1)))))));
1892}
1893
1894TEST(HasAnyConstructorInitializer, IsWritten) {
1895 static const char Code[] =
1896 "struct Bar { Bar(){} };"
1897 "class Foo {"
1898 " Foo() : foo_() { }"
1899 " Bar foo_;"
1900 " Bar bar_;"
1901 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001902 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001903 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001904 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001905 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001906 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001907 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1908}
1909
1910TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001911 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001912
1913 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
1914 EXPECT_TRUE(
1915 matches("class X { public: X(); }; void x() { new X(); }", New));
1916 EXPECT_TRUE(
1917 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1918 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
1919}
1920
1921TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001922 StatementMatcher New = constructExpr(
1923 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001924
1925 EXPECT_TRUE(
1926 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1927 New));
1928 EXPECT_TRUE(
1929 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1930 New));
1931 EXPECT_TRUE(
1932 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
1933 New));
1934
Daniel Jasper848cbe12012-09-18 13:09:13 +00001935 StatementMatcher WrongIndex = constructExpr(
1936 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001937 EXPECT_TRUE(
1938 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
1939 WrongIndex));
1940}
1941
1942TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001943 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001944
1945 EXPECT_TRUE(
1946 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1947 EXPECT_TRUE(
1948 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
1949 New));
1950}
1951
Daniel Jasper1dad1832012-07-10 20:20:19 +00001952TEST(Matcher, DeleteExpression) {
1953 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001954 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001955}
1956
Manuel Klimek04616e42012-07-06 05:48:52 +00001957TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001958 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001959
1960 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
1961 EXPECT_TRUE(
1962 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
1963 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
1964}
1965
1966TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001967 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001968 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
1969 // wide string
1970 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
1971 // with escaped characters
1972 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
1973 // no matching -- though the data type is the same, there is no string literal
1974 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
1975}
1976
1977TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001978 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001979 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
1980 // wide character
1981 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
1982 // wide character, Hex encoded, NOT MATCHED!
1983 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
1984 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
1985}
1986
1987TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001988 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001989 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
1990 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
1991 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
1992 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
1993
1994 // Non-matching cases (character literals, float and double)
1995 EXPECT_TRUE(notMatches("int i = L'a';",
1996 HasIntLiteral)); // this is actually a character
1997 // literal cast to int
1998 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
1999 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2000 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2001}
2002
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002003TEST(Matcher, FloatLiterals) {
2004 StatementMatcher HasFloatLiteral = floatLiteral();
2005 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2006 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2007 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2008 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2009 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
2010
2011 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
2012}
2013
Daniel Jasper5901e472012-10-01 13:40:41 +00002014TEST(Matcher, NullPtrLiteral) {
2015 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2016}
2017
Daniel Jasper87c3d362012-09-20 14:12:57 +00002018TEST(Matcher, AsmStatement) {
2019 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2020}
2021
Manuel Klimek04616e42012-07-06 05:48:52 +00002022TEST(Matcher, Conditions) {
2023 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2024
2025 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2026 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2027 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2028 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2029 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2030}
2031
Manuel Klimek909b5c942014-05-27 10:04:12 +00002032TEST(IfStmt, ChildTraversalMatchers) {
2033 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2034 ifStmt(hasThen(boolLiteral(equals(true))))));
2035 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2036 ifStmt(hasThen(boolLiteral(equals(true))))));
2037 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2038 ifStmt(hasElse(boolLiteral(equals(true))))));
2039 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2040 ifStmt(hasElse(boolLiteral(equals(true))))));
2041}
2042
Manuel Klimek04616e42012-07-06 05:48:52 +00002043TEST(MatchBinaryOperator, HasOperatorName) {
2044 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2045
2046 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2047 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2048}
2049
2050TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2051 StatementMatcher OperatorTrueFalse =
2052 binaryOperator(hasLHS(boolLiteral(equals(true))),
2053 hasRHS(boolLiteral(equals(false))));
2054
2055 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2056 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2057 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2058}
2059
2060TEST(MatchBinaryOperator, HasEitherOperand) {
2061 StatementMatcher HasOperand =
2062 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2063
2064 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2065 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2066 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2067}
2068
2069TEST(Matcher, BinaryOperatorTypes) {
2070 // Integration test that verifies the AST provides all binary operators in
2071 // a way we expect.
2072 // FIXME: Operator ','
2073 EXPECT_TRUE(
2074 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2075 EXPECT_TRUE(
2076 matches("bool b; bool c = (b = true);",
2077 binaryOperator(hasOperatorName("="))));
2078 EXPECT_TRUE(
2079 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2080 EXPECT_TRUE(
2081 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2082 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2083 EXPECT_TRUE(
2084 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2085 EXPECT_TRUE(
2086 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2087 EXPECT_TRUE(
2088 matches("int i = 1; int j = (i <<= 2);",
2089 binaryOperator(hasOperatorName("<<="))));
2090 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2091 EXPECT_TRUE(
2092 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2093 EXPECT_TRUE(
2094 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2095 EXPECT_TRUE(
2096 matches("int i = 1; int j = (i >>= 2);",
2097 binaryOperator(hasOperatorName(">>="))));
2098 EXPECT_TRUE(
2099 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2100 EXPECT_TRUE(
2101 matches("int i = 42; int j = (i ^= 42);",
2102 binaryOperator(hasOperatorName("^="))));
2103 EXPECT_TRUE(
2104 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2105 EXPECT_TRUE(
2106 matches("int i = 42; int j = (i %= 42);",
2107 binaryOperator(hasOperatorName("%="))));
2108 EXPECT_TRUE(
2109 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2110 EXPECT_TRUE(
2111 matches("bool b = true && false;",
2112 binaryOperator(hasOperatorName("&&"))));
2113 EXPECT_TRUE(
2114 matches("bool b = true; bool c = (b &= false);",
2115 binaryOperator(hasOperatorName("&="))));
2116 EXPECT_TRUE(
2117 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2118 EXPECT_TRUE(
2119 matches("bool b = true || false;",
2120 binaryOperator(hasOperatorName("||"))));
2121 EXPECT_TRUE(
2122 matches("bool b = true; bool c = (b |= false);",
2123 binaryOperator(hasOperatorName("|="))));
2124 EXPECT_TRUE(
2125 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2126 EXPECT_TRUE(
2127 matches("int i = 42; int j = (i *= 23);",
2128 binaryOperator(hasOperatorName("*="))));
2129 EXPECT_TRUE(
2130 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2131 EXPECT_TRUE(
2132 matches("int i = 42; int j = (i /= 23);",
2133 binaryOperator(hasOperatorName("/="))));
2134 EXPECT_TRUE(
2135 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2136 EXPECT_TRUE(
2137 matches("int i = 42; int j = (i += 23);",
2138 binaryOperator(hasOperatorName("+="))));
2139 EXPECT_TRUE(
2140 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2141 EXPECT_TRUE(
2142 matches("int i = 42; int j = (i -= 23);",
2143 binaryOperator(hasOperatorName("-="))));
2144 EXPECT_TRUE(
2145 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2146 binaryOperator(hasOperatorName("->*"))));
2147 EXPECT_TRUE(
2148 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2149 binaryOperator(hasOperatorName(".*"))));
2150
2151 // Member expressions as operators are not supported in matches.
2152 EXPECT_TRUE(
2153 notMatches("struct A { void x(A *a) { a->x(this); } };",
2154 binaryOperator(hasOperatorName("->"))));
2155
2156 // Initializer assignments are not represented as operator equals.
2157 EXPECT_TRUE(
2158 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2159
2160 // Array indexing is not represented as operator.
2161 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2162
2163 // Overloaded operators do not match at all.
2164 EXPECT_TRUE(notMatches(
2165 "struct A { bool operator&&(const A &a) const { return false; } };"
2166 "void x() { A a, b; a && b; }",
2167 binaryOperator()));
2168}
2169
2170TEST(MatchUnaryOperator, HasOperatorName) {
2171 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2172
2173 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2174 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2175}
2176
2177TEST(MatchUnaryOperator, HasUnaryOperand) {
2178 StatementMatcher OperatorOnFalse =
2179 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2180
2181 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2182 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2183}
2184
2185TEST(Matcher, UnaryOperatorTypes) {
2186 // Integration test that verifies the AST provides all unary operators in
2187 // a way we expect.
2188 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2189 EXPECT_TRUE(
2190 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2191 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2192 EXPECT_TRUE(
2193 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2194 EXPECT_TRUE(
2195 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2196 EXPECT_TRUE(
2197 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2198 EXPECT_TRUE(
2199 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2200 EXPECT_TRUE(
2201 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2202 EXPECT_TRUE(
2203 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2204 EXPECT_TRUE(
2205 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2206
2207 // We don't match conversion operators.
2208 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2209
2210 // Function calls are not represented as operator.
2211 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2212
2213 // Overloaded operators do not match at all.
2214 // FIXME: We probably want to add that.
2215 EXPECT_TRUE(notMatches(
2216 "struct A { bool operator!() const { return false; } };"
2217 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2218}
2219
2220TEST(Matcher, ConditionalOperator) {
2221 StatementMatcher Conditional = conditionalOperator(
2222 hasCondition(boolLiteral(equals(true))),
2223 hasTrueExpression(boolLiteral(equals(false))));
2224
2225 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2226 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2227 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2228
2229 StatementMatcher ConditionalFalse = conditionalOperator(
2230 hasFalseExpression(boolLiteral(equals(false))));
2231
2232 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2233 EXPECT_TRUE(
2234 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2235}
2236
Daniel Jasper1dad1832012-07-10 20:20:19 +00002237TEST(ArraySubscriptMatchers, ArraySubscripts) {
2238 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2239 arraySubscriptExpr()));
2240 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2241 arraySubscriptExpr()));
2242}
2243
2244TEST(ArraySubscriptMatchers, ArrayIndex) {
2245 EXPECT_TRUE(matches(
2246 "int i[2]; void f() { i[1] = 1; }",
2247 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2248 EXPECT_TRUE(matches(
2249 "int i[2]; void f() { 1[i] = 1; }",
2250 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2251 EXPECT_TRUE(notMatches(
2252 "int i[2]; void f() { i[1] = 1; }",
2253 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2254}
2255
2256TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2257 EXPECT_TRUE(matches(
2258 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002259 arraySubscriptExpr(hasBase(implicitCastExpr(
2260 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002261}
2262
Manuel Klimek04616e42012-07-06 05:48:52 +00002263TEST(Matcher, HasNameSupportsNamespaces) {
2264 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002265 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002266 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002267 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002268 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002269 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002270 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002271 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002272 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002273 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002274 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002275 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002276 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002277 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002278 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002279 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002280 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002281 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002282 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002283 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002284 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002285 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002286 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002287 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002288}
2289
2290TEST(Matcher, HasNameSupportsOuterClasses) {
2291 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002292 matches("class A { class B { class C; }; };",
2293 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002294 EXPECT_TRUE(
2295 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002296 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002297 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002298 matches("class A { class B { class C; }; };",
2299 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002300 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002301 matches("class A { class B { class C; }; };",
2302 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002303 EXPECT_TRUE(
2304 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002305 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002306 EXPECT_TRUE(
2307 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002308 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002309 EXPECT_TRUE(
2310 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002311 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002312 EXPECT_TRUE(
2313 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002314 recordDecl(hasName("::C"))));
2315 EXPECT_TRUE(
2316 notMatches("class A { class B { class C; }; };",
2317 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002318 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002319 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002320 EXPECT_TRUE(
2321 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002322 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002323}
2324
2325TEST(Matcher, IsDefinition) {
2326 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002327 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002328 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2329 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2330
2331 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002332 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002333 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2334 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2335
2336 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002337 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002338 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2339 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2340}
2341
2342TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002343 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002344 ofClass(hasName("X")))));
2345
2346 EXPECT_TRUE(
2347 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2348 EXPECT_TRUE(
2349 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2350 Constructor));
2351 EXPECT_TRUE(
2352 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2353 Constructor));
2354}
2355
2356TEST(Matcher, VisitsTemplateInstantiations) {
2357 EXPECT_TRUE(matches(
2358 "class A { public: void x(); };"
2359 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002360 "void f() { B<A> b; b.y(); }",
2361 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002362
2363 EXPECT_TRUE(matches(
2364 "class A { public: void x(); };"
2365 "class C {"
2366 " public:"
2367 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2368 "};"
2369 "void f() {"
2370 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002371 "}",
2372 recordDecl(hasName("C"),
2373 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002374}
2375
Daniel Jasper1dad1832012-07-10 20:20:19 +00002376TEST(Matcher, HandlesNullQualTypes) {
2377 // FIXME: Add a Type matcher so we can replace uses of this
2378 // variable with Type(True())
2379 const TypeMatcher AnyType = anything();
2380
2381 // We don't really care whether this matcher succeeds; we're testing that
2382 // it completes without crashing.
2383 EXPECT_TRUE(matches(
2384 "struct A { };"
2385 "template <typename T>"
2386 "void f(T t) {"
2387 " T local_t(t /* this becomes a null QualType in the AST */);"
2388 "}"
2389 "void g() {"
2390 " f(0);"
2391 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002392 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002393 anyOf(
2394 TypeMatcher(hasDeclaration(anything())),
2395 pointsTo(AnyType),
2396 references(AnyType)
2397 // Other QualType matchers should go here.
2398 ))))));
2399}
2400
Manuel Klimek04616e42012-07-06 05:48:52 +00002401// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002402AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002403 // Make sure all special variables are used: node, match_finder,
2404 // bound_nodes_builder, and the parameter named 'AMatcher'.
2405 return AMatcher.matches(Node, Finder, Builder);
2406}
2407
2408TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002409 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002410
2411 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002412 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002413
2414 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002415 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002416
2417 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002418 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002419}
2420
2421AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +00002422 polymorphicHas,
2423 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2424 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002425 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002426 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002427 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2428 ASTMatchFinder::BK_First);
2429}
2430
2431TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002432 DeclarationMatcher HasClassB =
2433 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002434
2435 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002436 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002437
2438 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002439 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002440
2441 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002442 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002443
2444 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002445 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002446
2447 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2448}
2449
2450TEST(For, FindsForLoops) {
2451 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2452 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002453 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2454 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002455 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002456}
2457
Daniel Jasper4e566c42012-07-12 08:50:38 +00002458TEST(For, ForLoopInternals) {
2459 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2460 forStmt(hasCondition(anything()))));
2461 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2462 forStmt(hasLoopInit(anything()))));
2463}
2464
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002465TEST(For, ForRangeLoopInternals) {
2466 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2467 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002468 EXPECT_TRUE(matches(
2469 "void f(){ int a[] {1, 2}; for (int i : a); }",
2470 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002471}
2472
Daniel Jasper4e566c42012-07-12 08:50:38 +00002473TEST(For, NegativeForLoopInternals) {
2474 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002475 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002476 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2477 forStmt(hasLoopInit(anything()))));
2478}
2479
Manuel Klimek04616e42012-07-06 05:48:52 +00002480TEST(For, ReportsNoFalsePositives) {
2481 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2482 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2483}
2484
2485TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002486 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2487 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2488 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002489}
2490
2491TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2492 // It's not a compound statement just because there's "{}" in the source
2493 // text. This is an AST search, not grep.
2494 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002495 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002496 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002497 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002498}
2499
Daniel Jasper4e566c42012-07-12 08:50:38 +00002500TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002501 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002502 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002503 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002504 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002505 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002506 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002507 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002508 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002509 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2510 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002511}
2512
2513TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2514 // The simplest case: every compound statement is in a function
2515 // definition, and the function body itself must be a compound
2516 // statement.
2517 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002518 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002519}
2520
2521TEST(HasAnySubstatement, IsNotRecursive) {
2522 // It's really "has any immediate substatement".
2523 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002524 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002525}
2526
2527TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2528 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002529 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002530}
2531
2532TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2533 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002534 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002535}
2536
2537TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2538 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002539 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002540 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002541 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002542}
2543
2544TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2545 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002546 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002547 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002548 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002549 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002550 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002551}
2552
2553TEST(StatementCountIs, WorksWithMultipleStatements) {
2554 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002555 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002556}
2557
2558TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2559 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002560 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002561 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002562 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002563 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002564 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002565 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002566 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002567}
2568
2569TEST(Member, WorksInSimplestCase) {
2570 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002571 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002572}
2573
2574TEST(Member, DoesNotMatchTheBaseExpression) {
2575 // Don't pick out the wrong part of the member expression, this should
2576 // be checking the member (name) only.
2577 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002578 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002579}
2580
2581TEST(Member, MatchesInMemberFunctionCall) {
2582 EXPECT_TRUE(matches("void f() {"
2583 " struct { void first() {}; } s;"
2584 " s.first();"
2585 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002586 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002587}
2588
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002589TEST(Member, MatchesMember) {
2590 EXPECT_TRUE(matches(
2591 "struct A { int i; }; void f() { A a; a.i = 2; }",
2592 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2593 EXPECT_TRUE(notMatches(
2594 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2595 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2596}
2597
Daniel Jasper639522c2013-02-25 12:02:08 +00002598TEST(Member, UnderstandsAccess) {
2599 EXPECT_TRUE(matches(
2600 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2601 EXPECT_TRUE(notMatches(
2602 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2603 EXPECT_TRUE(notMatches(
2604 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2605
2606 EXPECT_TRUE(notMatches(
2607 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2608 EXPECT_TRUE(notMatches(
2609 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2610 EXPECT_TRUE(matches(
2611 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2612
2613 EXPECT_TRUE(notMatches(
2614 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2615 EXPECT_TRUE(matches("class A { protected: int i; };",
2616 fieldDecl(isProtected(), hasName("i"))));
2617 EXPECT_TRUE(notMatches(
2618 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2619
2620 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2621 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2622 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2623 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2624}
2625
Dmitri Gribenko06963042012-08-18 00:29:27 +00002626TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002627 // Fails in C++11 mode
2628 EXPECT_TRUE(matchesConditionally(
2629 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2630 "class X { void *operator new(std::size_t); };",
2631 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002632
2633 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002634 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002635
Daniel Jasper5901e472012-10-01 13:40:41 +00002636 // Fails in C++11 mode
2637 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002638 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2639 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002640 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002641}
2642
Manuel Klimek04616e42012-07-06 05:48:52 +00002643TEST(HasObjectExpression, DoesNotMatchMember) {
2644 EXPECT_TRUE(notMatches(
2645 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002646 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002647}
2648
2649TEST(HasObjectExpression, MatchesBaseOfVariable) {
2650 EXPECT_TRUE(matches(
2651 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002652 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002653 EXPECT_TRUE(matches(
2654 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002655 memberExpr(hasObjectExpression(
2656 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002657}
2658
2659TEST(HasObjectExpression,
2660 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2661 EXPECT_TRUE(matches(
2662 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002663 memberExpr(hasObjectExpression(
2664 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002665 EXPECT_TRUE(matches(
2666 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002667 memberExpr(hasObjectExpression(
2668 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002669}
2670
2671TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002672 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2673 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2674 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2675 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002676}
2677
2678TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002679 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002680}
2681
2682TEST(IsConstQualified, MatchesConstInt) {
2683 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002684 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002685}
2686
2687TEST(IsConstQualified, MatchesConstPointer) {
2688 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002689 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002690}
2691
2692TEST(IsConstQualified, MatchesThroughTypedef) {
2693 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002694 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002695 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002696 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002697}
2698
2699TEST(IsConstQualified, DoesNotMatchInappropriately) {
2700 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002701 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002702 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002703 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002704}
2705
Sam Panzer80c13772012-08-16 16:58:10 +00002706TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002707 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2708 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2709 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2710 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002711}
2712TEST(CastExpression, MatchesImplicitCasts) {
2713 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002714 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002715 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002716 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002717}
2718
2719TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002720 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2721 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2722 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2723 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002724}
2725
Manuel Klimek04616e42012-07-06 05:48:52 +00002726TEST(ReinterpretCast, MatchesSimpleCase) {
2727 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002728 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002729}
2730
2731TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002732 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002733 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002734 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002735 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002736 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002737 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2738 "B b;"
2739 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002740 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002741}
2742
2743TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002744 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002745 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002746 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002747}
2748
2749TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002750 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002751 EXPECT_TRUE(
2752 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002753 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002754 EXPECT_TRUE(
2755 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002756 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002757}
2758
2759TEST(DynamicCast, MatchesSimpleCase) {
2760 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2761 "B b;"
2762 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002763 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002764}
2765
2766TEST(StaticCast, MatchesSimpleCase) {
2767 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002768 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002769}
2770
2771TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002772 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002773 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002774 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002775 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002776 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002777 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2778 "B b;"
2779 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002780 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002781}
2782
Daniel Jasper417f7762012-09-18 13:36:17 +00002783TEST(CStyleCast, MatchesSimpleCase) {
2784 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2785}
2786
2787TEST(CStyleCast, DoesNotMatchOtherCasts) {
2788 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2789 "char q, *r = const_cast<char*>(&q);"
2790 "void* s = reinterpret_cast<char*>(&s);"
2791 "struct B { virtual ~B() {} }; struct D : B {};"
2792 "B b;"
2793 "D* t = dynamic_cast<D*>(&b);",
2794 cStyleCastExpr()));
2795}
2796
Manuel Klimek04616e42012-07-06 05:48:52 +00002797TEST(HasDestinationType, MatchesSimpleCase) {
2798 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002799 staticCastExpr(hasDestinationType(
2800 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002801}
2802
Sam Panzer80c13772012-08-16 16:58:10 +00002803TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2804 // This test creates an implicit const cast.
2805 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002806 implicitCastExpr(
2807 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002808 // This test creates an implicit array-to-pointer cast.
2809 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002810 implicitCastExpr(hasImplicitDestinationType(
2811 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002812}
2813
2814TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2815 // This test creates an implicit cast from int to char.
2816 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002817 implicitCastExpr(hasImplicitDestinationType(
2818 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002819 // This test creates an implicit array-to-pointer cast.
2820 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002821 implicitCastExpr(hasImplicitDestinationType(
2822 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002823}
2824
2825TEST(ImplicitCast, MatchesSimpleCase) {
2826 // This test creates an implicit const cast.
2827 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002828 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002829 // This test creates an implicit cast from int to char.
2830 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002831 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002832 // This test creates an implicit array-to-pointer cast.
2833 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002834 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002835}
2836
2837TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002838 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002839 // are present, and that it ignores explicit and paren casts.
2840
2841 // These two test cases have no casts.
2842 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002843 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002844 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002845 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002846
2847 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002848 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002849 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002850 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002851
2852 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002853 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002854}
2855
2856TEST(IgnoringImpCasts, MatchesImpCasts) {
2857 // This test checks that ignoringImpCasts matches when implicit casts are
2858 // present and its inner matcher alone does not match.
2859 // Note that this test creates an implicit const cast.
2860 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002861 varDecl(hasInitializer(ignoringImpCasts(
2862 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002863 // This test creates an implict cast from int to char.
2864 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002865 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002866 integerLiteral(equals(0)))))));
2867}
2868
2869TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2870 // These tests verify that ignoringImpCasts does not match if the inner
2871 // matcher does not match.
2872 // Note that the first test creates an implicit const cast.
2873 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002874 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002875 unless(anything()))))));
2876 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002877 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002878 unless(anything()))))));
2879
2880 // These tests verify that ignoringImplictCasts does not look through explicit
2881 // casts or parentheses.
2882 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002883 varDecl(hasInitializer(ignoringImpCasts(
2884 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002885 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002886 varDecl(hasInitializer(ignoringImpCasts(
2887 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002888 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002889 varDecl(hasInitializer(ignoringImpCasts(
2890 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002891 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002892 varDecl(hasInitializer(ignoringImpCasts(
2893 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002894}
2895
2896TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2897 // This test verifies that expressions that do not have implicit casts
2898 // still match the inner matcher.
2899 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002900 varDecl(hasInitializer(ignoringImpCasts(
2901 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002902}
2903
2904TEST(IgnoringParenCasts, MatchesParenCasts) {
2905 // This test checks that ignoringParenCasts matches when parentheses and/or
2906 // casts are present and its inner matcher alone does not match.
2907 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002908 varDecl(hasInitializer(ignoringParenCasts(
2909 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002910 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002911 varDecl(hasInitializer(ignoringParenCasts(
2912 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002913
2914 // This test creates an implict cast from int to char in addition to the
2915 // parentheses.
2916 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002917 varDecl(hasInitializer(ignoringParenCasts(
2918 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002919
2920 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002921 varDecl(hasInitializer(ignoringParenCasts(
2922 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002923 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002924 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002925 integerLiteral(equals(0)))))));
2926}
2927
2928TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
2929 // This test verifies that expressions that do not have any casts still match.
2930 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002931 varDecl(hasInitializer(ignoringParenCasts(
2932 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002933}
2934
2935TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
2936 // These tests verify that ignoringImpCasts does not match if the inner
2937 // matcher does not match.
2938 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002939 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002940 unless(anything()))))));
2941
2942 // This test creates an implicit cast from int to char in addition to the
2943 // parentheses.
2944 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002945 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002946 unless(anything()))))));
2947
2948 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002949 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002950 unless(anything()))))));
2951}
2952
2953TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
2954 // This test checks that ignoringParenAndImpCasts matches when
2955 // parentheses and/or implicit casts are present and its inner matcher alone
2956 // does not match.
2957 // Note that this test creates an implicit const cast.
2958 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002959 varDecl(hasInitializer(ignoringParenImpCasts(
2960 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002961 // This test creates an implicit cast from int to char.
2962 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002963 varDecl(hasInitializer(ignoringParenImpCasts(
2964 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002965}
2966
2967TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
2968 // This test verifies that expressions that do not have parentheses or
2969 // implicit casts still match.
2970 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002971 varDecl(hasInitializer(ignoringParenImpCasts(
2972 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002973 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002974 varDecl(hasInitializer(ignoringParenImpCasts(
2975 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002976}
2977
2978TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
2979 // These tests verify that ignoringParenImpCasts does not match if
2980 // the inner matcher does not match.
2981 // This test creates an implicit cast.
2982 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002983 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002984 unless(anything()))))));
2985 // These tests verify that ignoringParenAndImplictCasts does not look
2986 // through explicit casts.
2987 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002988 varDecl(hasInitializer(ignoringParenImpCasts(
2989 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002990 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002991 varDecl(hasInitializer(ignoringParenImpCasts(
2992 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002993 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002994 varDecl(hasInitializer(ignoringParenImpCasts(
2995 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002996}
2997
Manuel Klimeke9235692012-07-25 10:02:02 +00002998TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002999 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3000 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003001 implicitCastExpr(
3002 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003003}
3004
Manuel Klimeke9235692012-07-25 10:02:02 +00003005TEST(HasSourceExpression, MatchesExplicitCasts) {
3006 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003007 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003008 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003009 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003010}
3011
Manuel Klimek04616e42012-07-06 05:48:52 +00003012TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003013 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003014}
3015
3016TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003017 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003018}
3019
3020TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003021 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003022}
3023
3024TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003025 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003026}
3027
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003028TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3029 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3030 "const Foo f = Foo();",
3031 varDecl(hasInitializer(exprWithCleanups()))));
3032 EXPECT_FALSE(matches("struct Foo { };"
3033 "const Foo f = Foo();",
3034 varDecl(hasInitializer(exprWithCleanups()))));
3035}
3036
Daniel Jasper1dad1832012-07-10 20:20:19 +00003037TEST(InitListExpression, MatchesInitListExpression) {
3038 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3039 initListExpr(hasType(asString("int [2]")))));
3040 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003041 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003042}
3043
3044TEST(UsingDeclaration, MatchesUsingDeclarations) {
3045 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3046 usingDecl()));
3047}
3048
3049TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3050 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3051 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3052}
3053
3054TEST(UsingDeclaration, MatchesSpecificTarget) {
3055 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3056 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003057 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003058 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3059 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003060 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003061}
3062
3063TEST(UsingDeclaration, ThroughUsingDeclaration) {
3064 EXPECT_TRUE(matches(
3065 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003066 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003067 EXPECT_TRUE(notMatches(
3068 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003069 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003070}
3071
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003072TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3073 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3074 usingDirectiveDecl()));
3075 EXPECT_FALSE(
3076 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3077}
3078
Sam Panzerd624bfb2012-08-16 17:20:59 +00003079TEST(SingleDecl, IsSingleDecl) {
3080 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003081 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003082 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3083 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3084 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3085 SingleDeclStmt));
3086}
3087
3088TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003089 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003090
3091 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003092 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003093 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003094 declStmt(containsDeclaration(0, MatchesInit),
3095 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003096 unsigned WrongIndex = 42;
3097 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003098 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003099 MatchesInit))));
3100}
3101
3102TEST(DeclCount, DeclCountIsCorrect) {
3103 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003104 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003105 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003106 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003107 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003108 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003109}
3110
Manuel Klimek04616e42012-07-06 05:48:52 +00003111TEST(While, MatchesWhileLoops) {
3112 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3113 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3114 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3115}
3116
3117TEST(Do, MatchesDoLoops) {
3118 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3119 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3120}
3121
3122TEST(Do, DoesNotMatchWhileLoops) {
3123 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3124}
3125
3126TEST(SwitchCase, MatchesCase) {
3127 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3128 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3129 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3130 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3131}
3132
Daniel Jasper87c3d362012-09-20 14:12:57 +00003133TEST(SwitchCase, MatchesSwitch) {
3134 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3135 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3136 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3137 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3138}
3139
Peter Collingbourne3154a102013-05-10 11:52:02 +00003140TEST(SwitchCase, MatchesEachCase) {
3141 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3142 switchStmt(forEachSwitchCase(caseStmt()))));
3143 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3144 switchStmt(forEachSwitchCase(caseStmt()))));
3145 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3146 switchStmt(forEachSwitchCase(caseStmt()))));
3147 EXPECT_TRUE(notMatches(
3148 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3149 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3150 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3151 switchStmt(forEachSwitchCase(
3152 caseStmt(hasCaseConstant(integerLiteral()))))));
3153 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3154 switchStmt(forEachSwitchCase(
3155 caseStmt(hasCaseConstant(integerLiteral()))))));
3156 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3157 switchStmt(forEachSwitchCase(
3158 caseStmt(hasCaseConstant(integerLiteral()))))));
3159 EXPECT_TRUE(matchAndVerifyResultTrue(
3160 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3161 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3162 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3163}
3164
Manuel Klimekba46fc02013-07-19 11:50:54 +00003165TEST(ForEachConstructorInitializer, MatchesInitializers) {
3166 EXPECT_TRUE(matches(
3167 "struct X { X() : i(42), j(42) {} int i, j; };",
3168 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3169}
3170
Daniel Jasper87c3d362012-09-20 14:12:57 +00003171TEST(ExceptionHandling, SimpleCases) {
3172 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3173 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3174 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3175 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3176 throwExpr()));
3177 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3178 throwExpr()));
3179}
3180
Manuel Klimek04616e42012-07-06 05:48:52 +00003181TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3182 EXPECT_TRUE(notMatches(
3183 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003184 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003185 EXPECT_TRUE(notMatches(
3186 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003187 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003188}
3189
3190TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3191 EXPECT_TRUE(matches(
3192 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003193 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003194}
3195
3196TEST(ForEach, BindsOneNode) {
3197 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003198 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003199 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003200}
3201
3202TEST(ForEach, BindsMultipleNodes) {
3203 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003204 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003205 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003206}
3207
3208TEST(ForEach, BindsRecursiveCombinations) {
3209 EXPECT_TRUE(matchAndVerifyResultTrue(
3210 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003211 recordDecl(hasName("C"),
3212 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003213 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003214}
3215
3216TEST(ForEachDescendant, BindsOneNode) {
3217 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003218 recordDecl(hasName("C"),
3219 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003220 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003221}
3222
Daniel Jasper94a56852012-11-16 18:39:22 +00003223TEST(ForEachDescendant, NestedForEachDescendant) {
3224 DeclarationMatcher m = recordDecl(
3225 isDefinition(), decl().bind("x"), hasName("C"));
3226 EXPECT_TRUE(matchAndVerifyResultTrue(
3227 "class A { class B { class C {}; }; };",
3228 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3229 new VerifyIdIsBoundTo<Decl>("x", "C")));
3230
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003231 // Check that a partial match of 'm' that binds 'x' in the
3232 // first part of anyOf(m, anything()) will not overwrite the
3233 // binding created by the earlier binding in the hasDescendant.
3234 EXPECT_TRUE(matchAndVerifyResultTrue(
3235 "class A { class B { class C {}; }; };",
3236 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3237 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003238}
3239
Manuel Klimek04616e42012-07-06 05:48:52 +00003240TEST(ForEachDescendant, BindsMultipleNodes) {
3241 EXPECT_TRUE(matchAndVerifyResultTrue(
3242 "class C { class D { int x; int y; }; "
3243 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003244 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003245 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003246}
3247
3248TEST(ForEachDescendant, BindsRecursiveCombinations) {
3249 EXPECT_TRUE(matchAndVerifyResultTrue(
3250 "class C { class D { "
3251 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003252 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3253 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003254 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003255}
3256
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003257TEST(ForEachDescendant, BindsCombinations) {
3258 EXPECT_TRUE(matchAndVerifyResultTrue(
3259 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3260 "(true) {} }",
3261 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3262 forEachDescendant(whileStmt().bind("while"))),
3263 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3264}
3265
3266TEST(Has, DoesNotDeleteBindings) {
3267 EXPECT_TRUE(matchAndVerifyResultTrue(
3268 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3269 new VerifyIdIsBoundTo<Decl>("x", 1)));
3270}
3271
3272TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3273 // Those matchers cover all the cases where an inner matcher is called
3274 // and there is not a 1:1 relationship between the match of the outer
3275 // matcher and the match of the inner matcher.
3276 // The pattern to look for is:
3277 // ... return InnerMatcher.matches(...); ...
3278 // In which case no special handling is needed.
3279 //
3280 // On the other hand, if there are multiple alternative matches
3281 // (for example forEach*) or matches might be discarded (for example has*)
3282 // the implementation must make sure that the discarded matches do not
3283 // affect the bindings.
3284 // When new such matchers are added, add a test here that:
3285 // - matches a simple node, and binds it as the first thing in the matcher:
3286 // recordDecl(decl().bind("x"), hasName("X")))
3287 // - uses the matcher under test afterwards in a way that not the first
3288 // alternative is matched; for anyOf, that means the first branch
3289 // would need to return false; for hasAncestor, it means that not
3290 // the direct parent matches the inner matcher.
3291
3292 EXPECT_TRUE(matchAndVerifyResultTrue(
3293 "class X { int y; };",
3294 recordDecl(
3295 recordDecl().bind("x"), hasName("::X"),
3296 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3297 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3298 EXPECT_TRUE(matchAndVerifyResultTrue(
3299 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3300 anyOf(unless(anything()), anything())),
3301 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3302 EXPECT_TRUE(matchAndVerifyResultTrue(
3303 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3304 classTemplateSpecializationDecl(
3305 decl().bind("x"),
3306 hasAnyTemplateArgument(refersToType(asString("int")))),
3307 new VerifyIdIsBoundTo<Decl>("x", 1)));
3308 EXPECT_TRUE(matchAndVerifyResultTrue(
3309 "class X { void f(); void g(); };",
3310 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3311 new VerifyIdIsBoundTo<Decl>("x", 1)));
3312 EXPECT_TRUE(matchAndVerifyResultTrue(
3313 "class X { X() : a(1), b(2) {} double a; int b; };",
3314 recordDecl(decl().bind("x"),
3315 has(constructorDecl(
3316 hasAnyConstructorInitializer(forField(hasName("b")))))),
3317 new VerifyIdIsBoundTo<Decl>("x", 1)));
3318 EXPECT_TRUE(matchAndVerifyResultTrue(
3319 "void x(int, int) { x(0, 42); }",
3320 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3321 new VerifyIdIsBoundTo<Expr>("x", 1)));
3322 EXPECT_TRUE(matchAndVerifyResultTrue(
3323 "void x(int, int y) {}",
3324 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3325 new VerifyIdIsBoundTo<Decl>("x", 1)));
3326 EXPECT_TRUE(matchAndVerifyResultTrue(
3327 "void x() { return; if (true) {} }",
3328 functionDecl(decl().bind("x"),
3329 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3330 new VerifyIdIsBoundTo<Decl>("x", 1)));
3331 EXPECT_TRUE(matchAndVerifyResultTrue(
3332 "namespace X { void b(int); void b(); }"
3333 "using X::b;",
3334 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3335 functionDecl(parameterCountIs(1))))),
3336 new VerifyIdIsBoundTo<Decl>("x", 1)));
3337 EXPECT_TRUE(matchAndVerifyResultTrue(
3338 "class A{}; class B{}; class C : B, A {};",
3339 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3340 new VerifyIdIsBoundTo<Decl>("x", 1)));
3341 EXPECT_TRUE(matchAndVerifyResultTrue(
3342 "class A{}; typedef A B; typedef A C; typedef A D;"
3343 "class E : A {};",
3344 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3345 new VerifyIdIsBoundTo<Decl>("x", 1)));
3346 EXPECT_TRUE(matchAndVerifyResultTrue(
3347 "class A { class B { void f() {} }; };",
3348 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3349 new VerifyIdIsBoundTo<Decl>("x", 1)));
3350 EXPECT_TRUE(matchAndVerifyResultTrue(
3351 "template <typename T> struct A { struct B {"
3352 " void f() { if(true) {} }"
3353 "}; };"
3354 "void t() { A<int>::B b; b.f(); }",
3355 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3356 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3357 EXPECT_TRUE(matchAndVerifyResultTrue(
3358 "class A {};",
3359 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3360 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003361 EXPECT_TRUE(matchAndVerifyResultTrue(
3362 "class A { A() : s(), i(42) {} const char *s; int i; };",
3363 constructorDecl(hasName("::A::A"), decl().bind("x"),
3364 forEachConstructorInitializer(forField(hasName("i")))),
3365 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003366}
3367
Daniel Jasper33806cd2012-11-11 22:14:55 +00003368TEST(ForEachDescendant, BindsCorrectNodes) {
3369 EXPECT_TRUE(matchAndVerifyResultTrue(
3370 "class C { void f(); int i; };",
3371 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3372 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3373 EXPECT_TRUE(matchAndVerifyResultTrue(
3374 "class C { void f() {} int i; };",
3375 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3376 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3377}
3378
Manuel Klimekabf43712013-02-04 10:59:20 +00003379TEST(FindAll, BindsNodeOnMatch) {
3380 EXPECT_TRUE(matchAndVerifyResultTrue(
3381 "class A {};",
3382 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3383 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3384}
3385
3386TEST(FindAll, BindsDescendantNodeOnMatch) {
3387 EXPECT_TRUE(matchAndVerifyResultTrue(
3388 "class A { int a; int b; };",
3389 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3390 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3391}
3392
3393TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3394 EXPECT_TRUE(matchAndVerifyResultTrue(
3395 "class A { int a; int b; };",
3396 recordDecl(hasName("::A"),
3397 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3398 fieldDecl().bind("v"))))),
3399 new VerifyIdIsBoundTo<Decl>("v", 3)));
3400
3401 EXPECT_TRUE(matchAndVerifyResultTrue(
3402 "class A { class B {}; class C {}; };",
3403 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3404 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3405}
3406
Manuel Klimek88b95872013-02-04 09:42:38 +00003407TEST(EachOf, TriggersForEachMatch) {
3408 EXPECT_TRUE(matchAndVerifyResultTrue(
3409 "class A { int a; int b; };",
3410 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3411 has(fieldDecl(hasName("b")).bind("v")))),
3412 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3413}
3414
3415TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3416 EXPECT_TRUE(matchAndVerifyResultTrue(
3417 "class A { int a; int c; };",
3418 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3419 has(fieldDecl(hasName("b")).bind("v")))),
3420 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3421 EXPECT_TRUE(matchAndVerifyResultTrue(
3422 "class A { int c; int b; };",
3423 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3424 has(fieldDecl(hasName("b")).bind("v")))),
3425 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3426 EXPECT_TRUE(notMatches(
3427 "class A { int c; int d; };",
3428 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3429 has(fieldDecl(hasName("b")).bind("v"))))));
3430}
Manuel Klimek04616e42012-07-06 05:48:52 +00003431
3432TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3433 // Make sure that we can both match the class by name (::X) and by the type
3434 // the template was instantiated with (via a field).
3435
3436 EXPECT_TRUE(matches(
3437 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003438 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003439
3440 EXPECT_TRUE(matches(
3441 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003442 recordDecl(isTemplateInstantiation(), hasDescendant(
3443 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003444}
3445
3446TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3447 EXPECT_TRUE(matches(
3448 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003449 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003450 isTemplateInstantiation())));
3451}
3452
3453TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3454 EXPECT_TRUE(matches(
3455 "template <typename T> class X { T t; }; class A {};"
3456 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003457 recordDecl(isTemplateInstantiation(), hasDescendant(
3458 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003459}
3460
3461TEST(IsTemplateInstantiation,
3462 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3463 EXPECT_TRUE(matches(
3464 "template <typename T> class X {};"
3465 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003466 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003467}
3468
3469TEST(IsTemplateInstantiation,
3470 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3471 EXPECT_TRUE(matches(
3472 "class A {};"
3473 "class X {"
3474 " template <typename U> class Y { U u; };"
3475 " Y<A> y;"
3476 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003477 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003478}
3479
3480TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3481 // FIXME: Figure out whether this makes sense. It doesn't affect the
3482 // normal use case as long as the uppermost instantiation always is marked
3483 // as template instantiation, but it might be confusing as a predicate.
3484 EXPECT_TRUE(matches(
3485 "class A {};"
3486 "template <typename T> class X {"
3487 " template <typename U> class Y { U u; };"
3488 " Y<T> y;"
3489 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003490 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003491}
3492
3493TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3494 EXPECT_TRUE(notMatches(
3495 "template <typename T> class X {}; class A {};"
3496 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003497 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003498}
3499
3500TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3501 EXPECT_TRUE(notMatches(
3502 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003503 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003504}
3505
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003506TEST(IsExplicitTemplateSpecialization,
3507 DoesNotMatchPrimaryTemplate) {
3508 EXPECT_TRUE(notMatches(
3509 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003510 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003511 EXPECT_TRUE(notMatches(
3512 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003513 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003514}
3515
3516TEST(IsExplicitTemplateSpecialization,
3517 DoesNotMatchExplicitTemplateInstantiations) {
3518 EXPECT_TRUE(notMatches(
3519 "template <typename T> class X {};"
3520 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003521 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003522 EXPECT_TRUE(notMatches(
3523 "template <typename T> void f(T t) {}"
3524 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003525 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003526}
3527
3528TEST(IsExplicitTemplateSpecialization,
3529 DoesNotMatchImplicitTemplateInstantiations) {
3530 EXPECT_TRUE(notMatches(
3531 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003532 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003533 EXPECT_TRUE(notMatches(
3534 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003535 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003536}
3537
3538TEST(IsExplicitTemplateSpecialization,
3539 MatchesExplicitTemplateSpecializations) {
3540 EXPECT_TRUE(matches(
3541 "template <typename T> class X {};"
3542 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003543 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003544 EXPECT_TRUE(matches(
3545 "template <typename T> void f(T t) {}"
3546 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003547 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003548}
3549
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003550TEST(HasAncenstor, MatchesDeclarationAncestors) {
3551 EXPECT_TRUE(matches(
3552 "class A { class B { class C {}; }; };",
3553 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3554}
3555
3556TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3557 EXPECT_TRUE(notMatches(
3558 "class A { class B { class C {}; }; };",
3559 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3560}
3561
3562TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3563 EXPECT_TRUE(matches(
3564 "class A { class B { void f() { C c; } class C {}; }; };",
3565 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3566 hasAncestor(recordDecl(hasName("A"))))))));
3567}
3568
3569TEST(HasAncenstor, MatchesStatementAncestors) {
3570 EXPECT_TRUE(matches(
3571 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003572 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003573}
3574
3575TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3576 EXPECT_TRUE(matches(
3577 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003578 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003579}
3580
3581TEST(HasAncestor, BindsRecursiveCombinations) {
3582 EXPECT_TRUE(matchAndVerifyResultTrue(
3583 "class C { class D { class E { class F { int y; }; }; }; };",
3584 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003585 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003586}
3587
3588TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3589 EXPECT_TRUE(matchAndVerifyResultTrue(
3590 "class C { class D { class E { class F { int y; }; }; }; };",
3591 fieldDecl(hasAncestor(
3592 decl(
3593 hasDescendant(recordDecl(isDefinition(),
3594 hasAncestor(recordDecl())))
3595 ).bind("d")
3596 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003597 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003598}
3599
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003600TEST(HasAncestor, MatchesClosestAncestor) {
3601 EXPECT_TRUE(matchAndVerifyResultTrue(
3602 "template <typename T> struct C {"
3603 " void f(int) {"
3604 " struct I { void g(T) { int x; } } i; i.g(42);"
3605 " }"
3606 "};"
3607 "template struct C<int>;",
3608 varDecl(hasName("x"),
3609 hasAncestor(functionDecl(hasParameter(
3610 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3611 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3612}
3613
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003614TEST(HasAncestor, MatchesInTemplateInstantiations) {
3615 EXPECT_TRUE(matches(
3616 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3617 "A<int>::B::C a;",
3618 fieldDecl(hasType(asString("int")),
3619 hasAncestor(recordDecl(hasName("A"))))));
3620}
3621
3622TEST(HasAncestor, MatchesInImplicitCode) {
3623 EXPECT_TRUE(matches(
3624 "struct X {}; struct A { A() {} X x; };",
3625 constructorDecl(
3626 hasAnyConstructorInitializer(withInitializer(expr(
3627 hasAncestor(recordDecl(hasName("A")))))))));
3628}
3629
Daniel Jasper632aea92012-10-22 16:26:51 +00003630TEST(HasParent, MatchesOnlyParent) {
3631 EXPECT_TRUE(matches(
3632 "void f() { if (true) { int x = 42; } }",
3633 compoundStmt(hasParent(ifStmt()))));
3634 EXPECT_TRUE(notMatches(
3635 "void f() { for (;;) { int x = 42; } }",
3636 compoundStmt(hasParent(ifStmt()))));
3637 EXPECT_TRUE(notMatches(
3638 "void f() { if (true) for (;;) { int x = 42; } }",
3639 compoundStmt(hasParent(ifStmt()))));
3640}
3641
Manuel Klimekc844a462012-12-06 14:42:48 +00003642TEST(HasAncestor, MatchesAllAncestors) {
3643 EXPECT_TRUE(matches(
3644 "template <typename T> struct C { static void f() { 42; } };"
3645 "void t() { C<int>::f(); }",
3646 integerLiteral(
3647 equals(42),
3648 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3649 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3650}
3651
3652TEST(HasParent, MatchesAllParents) {
3653 EXPECT_TRUE(matches(
3654 "template <typename T> struct C { static void f() { 42; } };"
3655 "void t() { C<int>::f(); }",
3656 integerLiteral(
3657 equals(42),
3658 hasParent(compoundStmt(hasParent(functionDecl(
3659 hasParent(recordDecl(isTemplateInstantiation())))))))));
3660 EXPECT_TRUE(matches(
3661 "template <typename T> struct C { static void f() { 42; } };"
3662 "void t() { C<int>::f(); }",
3663 integerLiteral(
3664 equals(42),
3665 hasParent(compoundStmt(hasParent(functionDecl(
3666 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3667 EXPECT_TRUE(matches(
3668 "template <typename T> struct C { static void f() { 42; } };"
3669 "void t() { C<int>::f(); }",
3670 integerLiteral(equals(42),
3671 hasParent(compoundStmt(allOf(
3672 hasParent(functionDecl(
3673 hasParent(recordDecl(isTemplateInstantiation())))),
3674 hasParent(functionDecl(hasParent(recordDecl(
3675 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003676 EXPECT_TRUE(
3677 notMatches("template <typename T> struct C { static void f() {} };"
3678 "void t() { C<int>::f(); }",
3679 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003680}
3681
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003682TEST(HasParent, NoDuplicateParents) {
3683 class HasDuplicateParents : public BoundNodesCallback {
3684 public:
3685 bool run(const BoundNodes *Nodes) override { return false; }
3686 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3687 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3688 std::set<const void *> Parents;
3689 for (const auto &Parent : Context->getParents(*Node)) {
3690 if (!Parents.insert(Parent.getMemoizationData()).second) {
3691 return true;
3692 }
3693 }
3694 return false;
3695 }
3696 };
3697 EXPECT_FALSE(matchAndVerifyResultTrue(
3698 "template <typename T> int Foo() { return 1 + 2; }\n"
3699 "int x = Foo<int>() + Foo<unsigned>();",
3700 stmt().bind("node"), new HasDuplicateParents()));
3701}
3702
Daniel Jasper516b02e2012-10-17 08:52:59 +00003703TEST(TypeMatching, MatchesTypes) {
3704 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3705}
3706
3707TEST(TypeMatching, MatchesArrayTypes) {
3708 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3709 EXPECT_TRUE(matches("int a[42];", arrayType()));
3710 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3711
3712 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3713 arrayType(hasElementType(builtinType()))));
3714
3715 EXPECT_TRUE(matches(
3716 "int const a[] = { 2, 3 };",
3717 qualType(arrayType(hasElementType(builtinType())))));
3718 EXPECT_TRUE(matches(
3719 "int const a[] = { 2, 3 };",
3720 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3721 EXPECT_TRUE(matches(
3722 "typedef const int T; T x[] = { 1, 2 };",
3723 qualType(isConstQualified(), arrayType())));
3724
3725 EXPECT_TRUE(notMatches(
3726 "int a[] = { 2, 3 };",
3727 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3728 EXPECT_TRUE(notMatches(
3729 "int a[] = { 2, 3 };",
3730 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3731 EXPECT_TRUE(notMatches(
3732 "int const a[] = { 2, 3 };",
3733 qualType(arrayType(hasElementType(builtinType())),
3734 unless(isConstQualified()))));
3735
3736 EXPECT_TRUE(matches("int a[2];",
3737 constantArrayType(hasElementType(builtinType()))));
3738 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3739}
3740
3741TEST(TypeMatching, MatchesComplexTypes) {
3742 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3743 EXPECT_TRUE(matches(
3744 "_Complex float f;",
3745 complexType(hasElementType(builtinType()))));
3746 EXPECT_TRUE(notMatches(
3747 "_Complex float f;",
3748 complexType(hasElementType(isInteger()))));
3749}
3750
3751TEST(TypeMatching, MatchesConstantArrayTypes) {
3752 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3753 EXPECT_TRUE(notMatches(
3754 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3755 constantArrayType(hasElementType(builtinType()))));
3756
3757 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3758 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3759 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3760}
3761
3762TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3763 EXPECT_TRUE(matches(
3764 "template <typename T, int Size> class array { T data[Size]; };",
3765 dependentSizedArrayType()));
3766 EXPECT_TRUE(notMatches(
3767 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3768 dependentSizedArrayType()));
3769}
3770
3771TEST(TypeMatching, MatchesIncompleteArrayType) {
3772 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3773 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3774
3775 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3776 incompleteArrayType()));
3777}
3778
3779TEST(TypeMatching, MatchesVariableArrayType) {
3780 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3781 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3782
3783 EXPECT_TRUE(matches(
3784 "void f(int b) { int a[b]; }",
3785 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3786 varDecl(hasName("b")))))))));
3787}
3788
3789TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003790 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3791 llvm::Triple::Win32) {
3792 // FIXME: Make this work for MSVC.
3793 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003794
David Majnemer197e2102014-03-05 06:32:38 +00003795 EXPECT_TRUE(matches("_Atomic(int) i;",
3796 atomicType(hasValueType(isInteger()))));
3797 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3798 atomicType(hasValueType(isInteger()))));
3799 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003800}
3801
3802TEST(TypeMatching, MatchesAutoTypes) {
3803 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3804 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3805 autoType()));
3806
Richard Smith061f1e22013-04-30 21:23:01 +00003807 // FIXME: Matching against the type-as-written can't work here, because the
3808 // type as written was not deduced.
3809 //EXPECT_TRUE(matches("auto a = 1;",
3810 // autoType(hasDeducedType(isInteger()))));
3811 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3812 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003813}
3814
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00003815TEST(TypeMatching, MatchesFunctionTypes) {
3816 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3817 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3818}
3819
Edwin Vaneec074802013-04-01 18:33:34 +00003820TEST(TypeMatching, MatchesParenType) {
3821 EXPECT_TRUE(
3822 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3823 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3824
3825 EXPECT_TRUE(matches(
3826 "int (*ptr_to_func)(int);",
3827 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3828 EXPECT_TRUE(notMatches(
3829 "int (*ptr_to_array)[4];",
3830 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3831}
3832
Daniel Jasper516b02e2012-10-17 08:52:59 +00003833TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003834 // FIXME: Reactive when these tests can be more specific (not matching
3835 // implicit code on certain platforms), likely when we have hasDescendant for
3836 // Types/TypeLocs.
3837 //EXPECT_TRUE(matchAndVerifyResultTrue(
3838 // "int* a;",
3839 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3840 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3841 //EXPECT_TRUE(matchAndVerifyResultTrue(
3842 // "int* a;",
3843 // pointerTypeLoc().bind("loc"),
3844 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003845 EXPECT_TRUE(matches(
3846 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003847 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003848 EXPECT_TRUE(matches(
3849 "int** a;",
3850 loc(pointerType(pointee(pointerType())))));
3851 EXPECT_TRUE(matches(
3852 "int* b; int* * const a = &b;",
3853 loc(qualType(isConstQualified(), pointerType()))));
3854
3855 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00003856 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3857 hasType(blockPointerType()))));
3858 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3859 hasType(memberPointerType()))));
3860 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3861 hasType(pointerType()))));
3862 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3863 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003864 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3865 hasType(lValueReferenceType()))));
3866 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3867 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003868
Daniel Jasper7943eb52012-10-17 13:35:36 +00003869 Fragment = "int *ptr;";
3870 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3871 hasType(blockPointerType()))));
3872 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3873 hasType(memberPointerType()))));
3874 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3875 hasType(pointerType()))));
3876 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3877 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003878
Daniel Jasper7943eb52012-10-17 13:35:36 +00003879 Fragment = "int a; int &ref = a;";
3880 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3881 hasType(blockPointerType()))));
3882 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3883 hasType(memberPointerType()))));
3884 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3885 hasType(pointerType()))));
3886 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3887 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003888 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3889 hasType(lValueReferenceType()))));
3890 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3891 hasType(rValueReferenceType()))));
3892
3893 Fragment = "int &&ref = 2;";
3894 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3895 hasType(blockPointerType()))));
3896 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3897 hasType(memberPointerType()))));
3898 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3899 hasType(pointerType()))));
3900 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3901 hasType(referenceType()))));
3902 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3903 hasType(lValueReferenceType()))));
3904 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3905 hasType(rValueReferenceType()))));
3906}
3907
3908TEST(TypeMatching, AutoRefTypes) {
3909 std::string Fragment = "auto a = 1;"
3910 "auto b = a;"
3911 "auto &c = a;"
3912 "auto &&d = c;"
3913 "auto &&e = 2;";
3914 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
3915 hasType(referenceType()))));
3916 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
3917 hasType(referenceType()))));
3918 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3919 hasType(referenceType()))));
3920 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3921 hasType(lValueReferenceType()))));
3922 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
3923 hasType(rValueReferenceType()))));
3924 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3925 hasType(referenceType()))));
3926 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3927 hasType(lValueReferenceType()))));
3928 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
3929 hasType(rValueReferenceType()))));
3930 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3931 hasType(referenceType()))));
3932 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
3933 hasType(lValueReferenceType()))));
3934 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3935 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003936}
3937
3938TEST(TypeMatching, PointeeTypes) {
3939 EXPECT_TRUE(matches("int b; int &a = b;",
3940 referenceType(pointee(builtinType()))));
3941 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
3942
3943 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003944 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003945
3946 EXPECT_TRUE(matches(
3947 "int const *A;",
3948 pointerType(pointee(isConstQualified(), builtinType()))));
3949 EXPECT_TRUE(notMatches(
3950 "int *A;",
3951 pointerType(pointee(isConstQualified(), builtinType()))));
3952}
3953
3954TEST(TypeMatching, MatchesPointersToConstTypes) {
3955 EXPECT_TRUE(matches("int b; int * const a = &b;",
3956 loc(pointerType())));
3957 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00003958 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003959 EXPECT_TRUE(matches(
3960 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00003961 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003962 EXPECT_TRUE(matches(
3963 "int b; const int * a = &b;",
3964 pointerType(pointee(builtinType()))));
3965}
3966
3967TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003968 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
3969 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003970}
3971
Edwin Vanef901b712013-02-25 14:49:29 +00003972TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00003973 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00003974 templateSpecializationType()));
3975}
3976
Edwin Vaneb6eae142013-02-25 20:43:32 +00003977TEST(TypeMatching, MatchesRecordType) {
3978 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00003979 EXPECT_TRUE(matches("struct S{}; S s;",
3980 recordType(hasDeclaration(recordDecl(hasName("S"))))));
3981 EXPECT_TRUE(notMatches("int i;",
3982 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00003983}
3984
3985TEST(TypeMatching, MatchesElaboratedType) {
3986 EXPECT_TRUE(matches(
3987 "namespace N {"
3988 " namespace M {"
3989 " class D {};"
3990 " }"
3991 "}"
3992 "N::M::D d;", elaboratedType()));
3993 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
3994 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
3995}
3996
3997TEST(ElaboratedTypeNarrowing, hasQualifier) {
3998 EXPECT_TRUE(matches(
3999 "namespace N {"
4000 " namespace M {"
4001 " class D {};"
4002 " }"
4003 "}"
4004 "N::M::D d;",
4005 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4006 EXPECT_TRUE(notMatches(
4007 "namespace M {"
4008 " class D {};"
4009 "}"
4010 "M::D d;",
4011 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004012 EXPECT_TRUE(notMatches(
4013 "struct D {"
4014 "} d;",
4015 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004016}
4017
4018TEST(ElaboratedTypeNarrowing, namesType) {
4019 EXPECT_TRUE(matches(
4020 "namespace N {"
4021 " namespace M {"
4022 " class D {};"
4023 " }"
4024 "}"
4025 "N::M::D d;",
4026 elaboratedType(elaboratedType(namesType(recordType(
4027 hasDeclaration(namedDecl(hasName("D")))))))));
4028 EXPECT_TRUE(notMatches(
4029 "namespace M {"
4030 " class D {};"
4031 "}"
4032 "M::D d;",
4033 elaboratedType(elaboratedType(namesType(typedefType())))));
4034}
4035
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004036TEST(NNS, MatchesNestedNameSpecifiers) {
4037 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4038 nestedNameSpecifier()));
4039 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4040 nestedNameSpecifier()));
4041 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4042 nestedNameSpecifier()));
4043
4044 EXPECT_TRUE(matches(
4045 "struct A { static void f() {} }; void g() { A::f(); }",
4046 nestedNameSpecifier()));
4047 EXPECT_TRUE(notMatches(
4048 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4049 nestedNameSpecifier()));
4050}
4051
Daniel Jasper87c3d362012-09-20 14:12:57 +00004052TEST(NullStatement, SimpleCases) {
4053 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4054 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4055}
4056
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004057TEST(NNS, MatchesTypes) {
4058 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4059 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4060 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4061 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4062 Matcher));
4063 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4064}
4065
4066TEST(NNS, MatchesNamespaceDecls) {
4067 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4068 specifiesNamespace(hasName("ns")));
4069 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4070 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4071 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4072}
4073
4074TEST(NNS, BindsNestedNameSpecifiers) {
4075 EXPECT_TRUE(matchAndVerifyResultTrue(
4076 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4077 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4078 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4079}
4080
4081TEST(NNS, BindsNestedNameSpecifierLocs) {
4082 EXPECT_TRUE(matchAndVerifyResultTrue(
4083 "namespace ns { struct B {}; } ns::B b;",
4084 loc(nestedNameSpecifier()).bind("loc"),
4085 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4086}
4087
4088TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4089 EXPECT_TRUE(matches(
4090 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4091 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4092 EXPECT_TRUE(matches(
4093 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004094 nestedNameSpecifierLoc(hasPrefix(
4095 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004096}
4097
Daniel Jasper6fc34332012-10-30 15:42:00 +00004098TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4099 std::string Fragment =
4100 "namespace a { struct A { struct B { struct C {}; }; }; };"
4101 "void f() { a::A::B::C c; }";
4102 EXPECT_TRUE(matches(
4103 Fragment,
4104 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4105 hasDescendant(nestedNameSpecifier(
4106 specifiesNamespace(hasName("a")))))));
4107 EXPECT_TRUE(notMatches(
4108 Fragment,
4109 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4110 has(nestedNameSpecifier(
4111 specifiesNamespace(hasName("a")))))));
4112 EXPECT_TRUE(matches(
4113 Fragment,
4114 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4115 has(nestedNameSpecifier(
4116 specifiesNamespace(hasName("a")))))));
4117
4118 // Not really useful because a NestedNameSpecifier can af at most one child,
4119 // but to complete the interface.
4120 EXPECT_TRUE(matchAndVerifyResultTrue(
4121 Fragment,
4122 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4123 forEach(nestedNameSpecifier().bind("x"))),
4124 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4125}
4126
4127TEST(NNS, NestedNameSpecifiersAsDescendants) {
4128 std::string Fragment =
4129 "namespace a { struct A { struct B { struct C {}; }; }; };"
4130 "void f() { a::A::B::C c; }";
4131 EXPECT_TRUE(matches(
4132 Fragment,
4133 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4134 asString("struct a::A")))))));
4135 EXPECT_TRUE(matchAndVerifyResultTrue(
4136 Fragment,
4137 functionDecl(hasName("f"),
4138 forEachDescendant(nestedNameSpecifier().bind("x"))),
4139 // Nested names: a, a::A and a::A::B.
4140 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4141}
4142
4143TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4144 std::string Fragment =
4145 "namespace a { struct A { struct B { struct C {}; }; }; };"
4146 "void f() { a::A::B::C c; }";
4147 EXPECT_TRUE(matches(
4148 Fragment,
4149 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4150 hasDescendant(loc(nestedNameSpecifier(
4151 specifiesNamespace(hasName("a"))))))));
4152 EXPECT_TRUE(notMatches(
4153 Fragment,
4154 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4155 has(loc(nestedNameSpecifier(
4156 specifiesNamespace(hasName("a"))))))));
4157 EXPECT_TRUE(matches(
4158 Fragment,
4159 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4160 has(loc(nestedNameSpecifier(
4161 specifiesNamespace(hasName("a"))))))));
4162
4163 EXPECT_TRUE(matchAndVerifyResultTrue(
4164 Fragment,
4165 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4166 forEach(nestedNameSpecifierLoc().bind("x"))),
4167 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4168}
4169
4170TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4171 std::string Fragment =
4172 "namespace a { struct A { struct B { struct C {}; }; }; };"
4173 "void f() { a::A::B::C c; }";
4174 EXPECT_TRUE(matches(
4175 Fragment,
4176 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4177 asString("struct a::A"))))))));
4178 EXPECT_TRUE(matchAndVerifyResultTrue(
4179 Fragment,
4180 functionDecl(hasName("f"),
4181 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4182 // Nested names: a, a::A and a::A::B.
4183 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4184}
4185
Manuel Klimek191c0932013-02-01 13:41:35 +00004186template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004187public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004188 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4189 StringRef InnerId)
4190 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004191 }
4192
Manuel Klimek191c0932013-02-01 13:41:35 +00004193 virtual bool run(const BoundNodes *Nodes) { return false; }
4194
Manuel Klimekc2687452012-10-24 14:47:44 +00004195 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4196 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004197 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4198 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004199 }
4200private:
4201 std::string Id;
4202 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004203 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004204};
4205
4206TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004207 EXPECT_TRUE(matchAndVerifyResultTrue(
4208 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4209 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004210 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4211 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004212 EXPECT_TRUE(matchAndVerifyResultFalse(
4213 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4214 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004215 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4216 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004217}
4218
4219TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004220 EXPECT_TRUE(matchAndVerifyResultTrue(
4221 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004222 new VerifyMatchOnNode<clang::Stmt>(
4223 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004224 EXPECT_TRUE(matchAndVerifyResultFalse(
4225 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004226 new VerifyMatchOnNode<clang::Stmt>(
4227 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004228}
4229
4230TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4231 EXPECT_TRUE(matchAndVerifyResultTrue(
4232 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4233 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004234 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004235 EXPECT_TRUE(matchAndVerifyResultFalse(
4236 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4237 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004238 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004239}
4240
Manuel Klimekbee08572013-02-07 12:42:10 +00004241template <typename T>
4242class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4243public:
4244 virtual bool run(const BoundNodes *Nodes) { return false; }
4245
4246 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4247 const T *Node = Nodes->getNodeAs<T>("");
4248 return verify(*Nodes, *Context, Node);
4249 }
4250
4251 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004252 // Use the original typed pointer to verify we can pass pointers to subtypes
4253 // to equalsNode.
4254 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004255 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004256 "", match(stmt(hasParent(
4257 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004258 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004259 }
4260 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004261 // Use the original typed pointer to verify we can pass pointers to subtypes
4262 // to equalsNode.
4263 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004264 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004265 "", match(decl(hasParent(
4266 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004267 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004268 }
4269};
4270
4271TEST(IsEqualTo, MatchesNodesByIdentity) {
4272 EXPECT_TRUE(matchAndVerifyResultTrue(
4273 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004274 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4275 EXPECT_TRUE(matchAndVerifyResultTrue(
4276 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4277 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004278}
4279
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004280class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4281public:
4282 VerifyStartOfTranslationUnit() : Called(false) {}
4283 virtual void run(const MatchFinder::MatchResult &Result) {
4284 EXPECT_TRUE(Called);
4285 }
4286 virtual void onStartOfTranslationUnit() {
4287 Called = true;
4288 }
4289 bool Called;
4290};
4291
4292TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4293 MatchFinder Finder;
4294 VerifyStartOfTranslationUnit VerifyCallback;
4295 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004296 std::unique_ptr<FrontendActionFactory> Factory(
4297 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004298 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4299 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004300
4301 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004302 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004303 ASSERT_TRUE(AST.get());
4304 Finder.matchAST(AST->getASTContext());
4305 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004306}
4307
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004308class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4309public:
4310 VerifyEndOfTranslationUnit() : Called(false) {}
4311 virtual void run(const MatchFinder::MatchResult &Result) {
4312 EXPECT_FALSE(Called);
4313 }
4314 virtual void onEndOfTranslationUnit() {
4315 Called = true;
4316 }
4317 bool Called;
4318};
4319
4320TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4321 MatchFinder Finder;
4322 VerifyEndOfTranslationUnit VerifyCallback;
4323 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004324 std::unique_ptr<FrontendActionFactory> Factory(
4325 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004326 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4327 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004328
4329 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004330 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004331 ASSERT_TRUE(AST.get());
4332 Finder.matchAST(AST->getASTContext());
4333 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004334}
4335
Manuel Klimekbbb75852013-06-20 14:06:32 +00004336TEST(EqualsBoundNodeMatcher, QualType) {
4337 EXPECT_TRUE(matches(
4338 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4339 hasInitializer(ignoringParenImpCasts(
4340 hasType(qualType(equalsBoundNode("type"))))))));
4341 EXPECT_TRUE(notMatches("int i = 1.f;",
4342 varDecl(hasType(qualType().bind("type")),
4343 hasInitializer(ignoringParenImpCasts(hasType(
4344 qualType(equalsBoundNode("type"))))))));
4345}
4346
4347TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4348 EXPECT_TRUE(notMatches(
4349 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4350 hasInitializer(ignoringParenImpCasts(
4351 hasType(qualType(equalsBoundNode("type"))))))));
4352}
4353
4354TEST(EqualsBoundNodeMatcher, Stmt) {
4355 EXPECT_TRUE(
4356 matches("void f() { if(true) {} }",
4357 stmt(allOf(ifStmt().bind("if"),
4358 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4359
4360 EXPECT_TRUE(notMatches(
4361 "void f() { if(true) { if (true) {} } }",
4362 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4363}
4364
4365TEST(EqualsBoundNodeMatcher, Decl) {
4366 EXPECT_TRUE(matches(
4367 "class X { class Y {}; };",
4368 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4369 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4370
4371 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4372 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4373 has(decl(equalsBoundNode("record")))))));
4374}
4375
4376TEST(EqualsBoundNodeMatcher, Type) {
4377 EXPECT_TRUE(matches(
4378 "class X { int a; int b; };",
4379 recordDecl(
4380 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4381 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4382
4383 EXPECT_TRUE(notMatches(
4384 "class X { int a; double b; };",
4385 recordDecl(
4386 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4387 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4388}
4389
4390TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004391 EXPECT_TRUE(matchAndVerifyResultTrue(
4392 "int f() {"
4393 " if (1) {"
4394 " int i = 9;"
4395 " }"
4396 " int j = 10;"
4397 " {"
4398 " float k = 9.0;"
4399 " }"
4400 " return 0;"
4401 "}",
4402 // Look for variable declarations within functions whose type is the same
4403 // as the function return type.
4404 functionDecl(returns(qualType().bind("type")),
4405 forEachDescendant(varDecl(hasType(
4406 qualType(equalsBoundNode("type")))).bind("decl"))),
4407 // Only i and j should match, not k.
4408 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4409}
4410
4411TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4412 EXPECT_TRUE(matchAndVerifyResultTrue(
4413 "void f() {"
4414 " int x;"
4415 " double d;"
4416 " x = d + x - d + x;"
4417 "}",
4418 functionDecl(
4419 hasName("f"), forEachDescendant(varDecl().bind("d")),
4420 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4421 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4422}
4423
Manuel Klimekce68f772014-03-25 14:39:26 +00004424TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4425 EXPECT_TRUE(matchAndVerifyResultTrue(
4426 "struct StringRef { int size() const; const char* data() const; };"
4427 "void f(StringRef v) {"
4428 " v.data();"
4429 "}",
4430 memberCallExpr(
4431 callee(methodDecl(hasName("data"))),
4432 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4433 .bind("var")))),
4434 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4435 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4436 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4437 .bind("data"),
4438 new VerifyIdIsBoundTo<Expr>("data", 1)));
4439
4440 EXPECT_FALSE(matches(
4441 "struct StringRef { int size() const; const char* data() const; };"
4442 "void f(StringRef v) {"
4443 " v.data();"
4444 " v.size();"
4445 "}",
4446 memberCallExpr(
4447 callee(methodDecl(hasName("data"))),
4448 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4449 .bind("var")))),
4450 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4451 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4452 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4453 .bind("data")));
4454}
4455
Manuel Klimek04616e42012-07-06 05:48:52 +00004456} // end namespace ast_matchers
4457} // end namespace clang