blob: 03acfe3060cb83a1b095c524e8719220d386dc8f [file] [log] [blame]
Manuel Klimek04616e42012-07-06 05:48:52 +00001//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher unit tests ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ASTMatchersTest.h"
Benjamin Kramere5015e52012-12-01 17:22:05 +000011#include "clang/AST/PrettyPrinter.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Chandler Carruth320d9662012-12-04 09:45:34 +000013#include "clang/ASTMatchers/ASTMatchers.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000014#include "clang/Tooling/Tooling.h"
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +000015#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000017#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000022#if GTEST_HAS_DEATH_TEST
Manuel Klimek04616e42012-07-06 05:48:52 +000023TEST(HasNameDeathTest, DiesOnEmptyName) {
24 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000025 DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000026 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27 }, "");
28}
29
Daniel Jasper1dad1832012-07-10 20:20:19 +000030TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000032 DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
Daniel Jasper1dad1832012-07-10 20:20:19 +000033 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34 }, "");
35}
36
Manuel Klimek04616e42012-07-06 05:48:52 +000037TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000039 DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000040 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41 }, "");
42}
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000043#endif
Manuel Klimek04616e42012-07-06 05:48:52 +000044
Peter Collingbourne2b9471302013-11-07 22:30:32 +000045TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46 MatchFinder Finder;
Craig Topper416fa342014-06-08 08:38:12 +000047 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50 nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000051
52 // Do not accept non-toplevel matchers.
Craig Topper416fa342014-06-08 08:38:12 +000053 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54 EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000056}
57
Manuel Klimeke9235692012-07-25 10:02:02 +000058TEST(Decl, MatchesDeclarations) {
59 EXPECT_TRUE(notMatches("", decl(usingDecl())));
60 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
61 decl(usingDecl())));
62}
63
Manuel Klimek04616e42012-07-06 05:48:52 +000064TEST(NameableDeclaration, MatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000065 DeclarationMatcher NamedX = namedDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +000066 EXPECT_TRUE(matches("typedef int X;", NamedX));
67 EXPECT_TRUE(matches("int X;", NamedX));
68 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
69 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
70 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
71 EXPECT_TRUE(matches("namespace X { }", NamedX));
Daniel Jasper1dad1832012-07-10 20:20:19 +000072 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
Manuel Klimek04616e42012-07-06 05:48:52 +000073
74 EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
Daniel Jasper1dad1832012-07-10 20:20:19 +000077TEST(NameableDeclaration, REMatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000078 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000079 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
80 EXPECT_TRUE(matches("int Xb;", NamedX));
81 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
82 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
83 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
84 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
85 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
86
87 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
88
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000089 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000090 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
91 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
92
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000093 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000094 EXPECT_TRUE(matches("int abc;", Abc));
95 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
96 EXPECT_TRUE(notMatches("int cab;", Abc));
97 EXPECT_TRUE(matches("int cabc;", Abc));
Manuel Klimeke792efd2012-12-10 07:08:53 +000098
99 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
100 EXPECT_TRUE(matches("int k;", StartsWithK));
101 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
102 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
103 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
104 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000105}
106
Manuel Klimek04616e42012-07-06 05:48:52 +0000107TEST(DeclarationMatcher, MatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000108 DeclarationMatcher ClassMatcher(recordDecl());
Saleem Abdulrasool377066a2014-03-27 22:50:18 +0000109 llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110 if (Triple.getOS() != llvm::Triple::Win32 ||
111 Triple.getEnvironment() != llvm::Triple::MSVC)
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +0000112 EXPECT_FALSE(matches("", ClassMatcher));
113 else
114 // Matches class type_info.
115 EXPECT_TRUE(matches("", ClassMatcher));
Manuel Klimek04616e42012-07-06 05:48:52 +0000116
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000117 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000118 EXPECT_TRUE(matches("class X;", ClassX));
119 EXPECT_TRUE(matches("class X {};", ClassX));
120 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
121 EXPECT_TRUE(notMatches("", ClassX));
122}
123
124TEST(DeclarationMatcher, ClassIsDerived) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000125 DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000126
127 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000128 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
Manuel Klimek04616e42012-07-06 05:48:52 +0000130 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131 EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
Daniel Jasperd6b82cb2012-09-12 21:14:15 +0000133 DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000134
135 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
136 EXPECT_TRUE(matches("class X {};", IsAX));
137 EXPECT_TRUE(matches("class X;", IsAX));
138 EXPECT_TRUE(notMatches("class Y;", IsAX));
139 EXPECT_TRUE(notMatches("", IsAX));
140
Manuel Klimek04616e42012-07-06 05:48:52 +0000141 DeclarationMatcher ZIsDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000142 recordDecl(hasName("Z"), isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000143 EXPECT_TRUE(
144 matches("class X {}; class Y : public X {}; class Z : public Y {};",
145 ZIsDerivedFromX));
146 EXPECT_TRUE(
147 matches("class X {};"
148 "template<class T> class Y : public X {};"
149 "class Z : public Y<int> {};", ZIsDerivedFromX));
150 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
151 ZIsDerivedFromX));
152 EXPECT_TRUE(
153 matches("template<class T> class X {}; "
154 "template<class T> class Z : public X<T> {};",
155 ZIsDerivedFromX));
156 EXPECT_TRUE(
157 matches("template<class T, class U=T> class X {}; "
158 "template<class T> class Z : public X<T> {};",
159 ZIsDerivedFromX));
160 EXPECT_TRUE(
161 notMatches("template<class X> class A { class Z : public X {}; };",
162 ZIsDerivedFromX));
163 EXPECT_TRUE(
164 matches("template<class X> class A { public: class Z : public X {}; }; "
165 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
166 EXPECT_TRUE(
167 matches("template <class T> class X {}; "
168 "template<class Y> class A { class Z : public X<Y> {}; };",
169 ZIsDerivedFromX));
170 EXPECT_TRUE(
171 notMatches("template<template<class T> class X> class A { "
172 " class Z : public X<int> {}; };", ZIsDerivedFromX));
173 EXPECT_TRUE(
174 matches("template<template<class T> class X> class A { "
175 " public: class Z : public X<int> {}; }; "
176 "template<class T> class X {}; void y() { A<X>::Z z; }",
177 ZIsDerivedFromX));
178 EXPECT_TRUE(
179 notMatches("template<class X> class A { class Z : public X::D {}; };",
180 ZIsDerivedFromX));
181 EXPECT_TRUE(
182 matches("template<class X> class A { public: "
183 " class Z : public X::D {}; }; "
184 "class Y { public: class X {}; typedef X D; }; "
185 "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
186 EXPECT_TRUE(
187 matches("class X {}; typedef X Y; class Z : public Y {};",
188 ZIsDerivedFromX));
189 EXPECT_TRUE(
190 matches("template<class T> class Y { typedef typename T::U X; "
191 " class Z : public X {}; };", ZIsDerivedFromX));
192 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
193 ZIsDerivedFromX));
194 EXPECT_TRUE(
195 notMatches("template<class T> class X {}; "
196 "template<class T> class A { class Z : public X<T>::D {}; };",
197 ZIsDerivedFromX));
198 EXPECT_TRUE(
199 matches("template<class T> class X { public: typedef X<T> D; }; "
200 "template<class T> class A { public: "
201 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
202 ZIsDerivedFromX));
203 EXPECT_TRUE(
204 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
205 ZIsDerivedFromX));
206 EXPECT_TRUE(
207 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
208 ZIsDerivedFromX));
209 EXPECT_TRUE(
210 matches("class X {}; class Y : public X {}; "
211 "typedef Y V; typedef V W; class Z : public W {};",
212 ZIsDerivedFromX));
213 EXPECT_TRUE(
214 matches("template<class T, class U> class X {}; "
215 "template<class T> class A { class Z : public X<T, int> {}; };",
216 ZIsDerivedFromX));
217 EXPECT_TRUE(
218 notMatches("template<class X> class D { typedef X A; typedef A B; "
219 " typedef B C; class Z : public C {}; };",
220 ZIsDerivedFromX));
221 EXPECT_TRUE(
222 matches("class X {}; typedef X A; typedef A B; "
223 "class Z : public B {};", ZIsDerivedFromX));
224 EXPECT_TRUE(
225 matches("class X {}; typedef X A; typedef A B; typedef B C; "
226 "class Z : public C {};", ZIsDerivedFromX));
227 EXPECT_TRUE(
228 matches("class U {}; typedef U X; typedef X V; "
229 "class Z : public V {};", ZIsDerivedFromX));
230 EXPECT_TRUE(
231 matches("class Base {}; typedef Base X; "
232 "class Z : public Base {};", ZIsDerivedFromX));
233 EXPECT_TRUE(
234 matches("class Base {}; typedef Base Base2; typedef Base2 X; "
235 "class Z : public Base {};", ZIsDerivedFromX));
236 EXPECT_TRUE(
237 notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
238 "class Z : public Base {};", ZIsDerivedFromX));
239 EXPECT_TRUE(
240 matches("class A {}; typedef A X; typedef A Y; "
241 "class Z : public Y {};", ZIsDerivedFromX));
242 EXPECT_TRUE(
243 notMatches("template <typename T> class Z;"
244 "template <> class Z<void> {};"
245 "template <typename T> class Z : public Z<void> {};",
246 IsDerivedFromX));
247 EXPECT_TRUE(
248 matches("template <typename T> class X;"
249 "template <> class X<void> {};"
250 "template <typename T> class X : public X<void> {};",
251 IsDerivedFromX));
252 EXPECT_TRUE(matches(
253 "class X {};"
254 "template <typename T> class Z;"
255 "template <> class Z<void> {};"
256 "template <typename T> class Z : public Z<void>, public X {};",
257 ZIsDerivedFromX));
Manuel Klimek5472a522012-12-04 13:40:29 +0000258 EXPECT_TRUE(
259 notMatches("template<int> struct X;"
260 "template<int i> struct X : public X<i-1> {};",
261 recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
262 EXPECT_TRUE(matches(
263 "struct A {};"
264 "template<int> struct X;"
265 "template<int i> struct X : public X<i-1> {};"
266 "template<> struct X<0> : public A {};"
267 "struct B : public X<42> {};",
268 recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000269
270 // FIXME: Once we have better matchers for template type matching,
271 // get rid of the Variable(...) matching and match the right template
272 // declarations directly.
273 const char *RecursiveTemplateOneParameter =
274 "class Base1 {}; class Base2 {};"
275 "template <typename T> class Z;"
276 "template <> class Z<void> : public Base1 {};"
277 "template <> class Z<int> : public Base2 {};"
278 "template <> class Z<float> : public Z<void> {};"
279 "template <> class Z<double> : public Z<int> {};"
280 "template <typename T> class Z : public Z<float>, public Z<double> {};"
281 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
282 EXPECT_TRUE(matches(
283 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000284 varDecl(hasName("z_float"),
285 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000286 EXPECT_TRUE(notMatches(
287 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000288 varDecl(hasName("z_float"),
289 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000290 EXPECT_TRUE(matches(
291 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000292 varDecl(hasName("z_char"),
293 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
294 isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000295
296 const char *RecursiveTemplateTwoParameters =
297 "class Base1 {}; class Base2 {};"
298 "template <typename T1, typename T2> class Z;"
299 "template <typename T> class Z<void, T> : public Base1 {};"
300 "template <typename T> class Z<int, T> : public Base2 {};"
301 "template <typename T> class Z<float, T> : public Z<void, T> {};"
302 "template <typename T> class Z<double, T> : public Z<int, T> {};"
303 "template <typename T1, typename T2> class Z : "
304 " public Z<float, T2>, public Z<double, T2> {};"
305 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
306 " Z<char, void> z_char; }";
307 EXPECT_TRUE(matches(
308 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000309 varDecl(hasName("z_float"),
310 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000311 EXPECT_TRUE(notMatches(
312 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000313 varDecl(hasName("z_float"),
314 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000315 EXPECT_TRUE(matches(
316 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000317 varDecl(hasName("z_char"),
318 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
319 isDerivedFrom("Base2")))))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000322 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000325 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000329 recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
Manuel Klimek1863e502013-08-02 21:24:09 +0000330
331 EXPECT_TRUE(matches(
332 "template<typename T> class X {};"
333 "template<typename T> using Z = X<T>;"
334 "template <typename T> class Y : Z<T> {};",
335 recordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000336}
337
Edwin Vane0a4836e2013-03-06 17:02:57 +0000338TEST(DeclarationMatcher, hasMethod) {
339 EXPECT_TRUE(matches("class A { void func(); };",
340 recordDecl(hasMethod(hasName("func")))));
341 EXPECT_TRUE(notMatches("class A { void func(); };",
342 recordDecl(hasMethod(isPublic()))));
343}
344
Daniel Jasper83dafaf2012-09-18 14:17:42 +0000345TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
346 EXPECT_TRUE(matches(
347 "template <typename T> struct A {"
348 " template <typename T2> struct F {};"
349 "};"
350 "template <typename T> struct B : A<T>::template F<T> {};"
351 "B<int> b;",
352 recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
353}
354
Edwin Vaneb6eae142013-02-25 20:43:32 +0000355TEST(DeclarationMatcher, hasDeclContext) {
356 EXPECT_TRUE(matches(
357 "namespace N {"
358 " namespace M {"
359 " class D {};"
360 " }"
361 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000362 recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000363 EXPECT_TRUE(notMatches(
364 "namespace N {"
365 " namespace M {"
366 " class D {};"
367 " }"
368 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000369 recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
370
371 EXPECT_TRUE(matches("namespace {"
372 " namespace M {"
373 " class D {};"
374 " }"
375 "}",
376 recordDecl(hasDeclContext(namespaceDecl(
377 hasName("M"), hasDeclContext(namespaceDecl()))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000378}
379
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000380TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000381 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000382 EXPECT_TRUE(notMatches("class X;", ClassX));
383 EXPECT_TRUE(notMatches("class X {};", ClassX));
384}
385
386TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000387 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000388 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
389 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
390}
391
392TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
393 EXPECT_TRUE(notMatches("template<typename T> class X { };"
394 "template<> class X<int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000395 classTemplateDecl(hasName("X"),
396 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000397}
398
399TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
400 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
401 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000402 classTemplateDecl(hasName("X"),
403 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000404}
405
Daniel Jasper4e566c42012-07-12 08:50:38 +0000406TEST(AllOf, AllOverloadsWork) {
407 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000408 "struct T { };"
409 "int f(int, T*, int, int);"
410 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000411 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000412 callExpr(allOf(callee(functionDecl(hasName("f"))),
413 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000414 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000415 callExpr(allOf(callee(functionDecl(hasName("f"))),
416 hasArgument(0, declRefExpr(to(varDecl()))),
417 hasArgument(1, hasType(pointsTo(
418 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000419 EXPECT_TRUE(matches(Program,
420 callExpr(allOf(callee(functionDecl(hasName("f"))),
421 hasArgument(0, declRefExpr(to(varDecl()))),
422 hasArgument(1, hasType(pointsTo(
423 recordDecl(hasName("T"))))),
424 hasArgument(2, integerLiteral(equals(3)))))));
425 EXPECT_TRUE(matches(Program,
426 callExpr(allOf(callee(functionDecl(hasName("f"))),
427 hasArgument(0, declRefExpr(to(varDecl()))),
428 hasArgument(1, hasType(pointsTo(
429 recordDecl(hasName("T"))))),
430 hasArgument(2, integerLiteral(equals(3))),
431 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000432}
433
Manuel Klimek04616e42012-07-06 05:48:52 +0000434TEST(DeclarationMatcher, MatchAnyOf) {
435 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000436 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000437 EXPECT_TRUE(
438 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
439 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
440 EXPECT_TRUE(
441 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
442 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
443
Daniel Jasper84c763e2012-07-15 19:57:12 +0000444 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000445 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000446 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
447 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
448
Manuel Klimek04616e42012-07-06 05:48:52 +0000449 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000450 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
451 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000452 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
453 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
454 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
455 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
456 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
457 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
458}
459
460TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000461 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000462 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
463 EXPECT_TRUE(matches("class X {};", HasClassX));
464
465 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000466 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000467 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
468 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
469 EXPECT_TRUE(
470 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
471}
472
473TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
474 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000475 recordDecl(
476 has(recordDecl(
477 has(recordDecl(hasName("X"))),
478 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000479 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000480 has(recordDecl(
481 has(recordDecl(hasName("A"))),
482 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000483 hasName("C"))),
484 hasName("F"));
485
486 EXPECT_TRUE(matches(
487 "class F {"
488 " class Z {"
489 " class X {};"
490 " class Y {};"
491 " };"
492 " class C {"
493 " class A {};"
494 " class B {};"
495 " };"
496 "};", Recursive));
497
498 EXPECT_TRUE(matches(
499 "class F {"
500 " class Z {"
501 " class A {};"
502 " class X {};"
503 " class Y {};"
504 " };"
505 " class C {"
506 " class X {};"
507 " class A {};"
508 " class B {};"
509 " };"
510 "};", Recursive));
511
512 EXPECT_TRUE(matches(
513 "class O1 {"
514 " class O2 {"
515 " class F {"
516 " class Z {"
517 " class A {};"
518 " class X {};"
519 " class Y {};"
520 " };"
521 " class C {"
522 " class X {};"
523 " class A {};"
524 " class B {};"
525 " };"
526 " };"
527 " };"
528 "};", Recursive));
529}
530
531TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
532 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000533 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000534 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000535 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000536 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000537 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000538 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000539 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000540 hasName("Y"))),
541 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000542 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000543 anyOf(
544 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000545 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000546 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000547 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000548 hasName("B")))))),
549 hasName("F")));
550
551 EXPECT_TRUE(matches("class F {};", Recursive));
552 EXPECT_TRUE(matches("class Z {};", Recursive));
553 EXPECT_TRUE(matches("class C {};", Recursive));
554 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
555 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
556 EXPECT_TRUE(
557 matches("class O1 { class O2 {"
558 " class M { class N { class B {}; }; }; "
559 "}; };", Recursive));
560}
561
562TEST(DeclarationMatcher, MatchNot) {
563 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000564 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000565 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000566 unless(hasName("X")));
567 EXPECT_TRUE(notMatches("", NotClassX));
568 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
569 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
570 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
571 EXPECT_TRUE(
572 notMatches("class Y {}; class Z {}; class X : public Y {};",
573 NotClassX));
574
575 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000576 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000577 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000578 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000579 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000580 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000581 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
582 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
583 ClassXHasNotClassY));
584}
585
586TEST(DeclarationMatcher, HasDescendant) {
587 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000588 recordDecl(
589 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000590 hasName("Z"));
591 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
592 EXPECT_TRUE(
593 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
594 EXPECT_TRUE(
595 matches("class Z { class A { class Y { class X {}; }; }; };",
596 ZDescendantClassX));
597 EXPECT_TRUE(
598 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
599 ZDescendantClassX));
600 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
601
602 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000603 recordDecl(
604 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000605 hasName("X"))),
606 hasName("Z"));
607 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
608 ZDescendantClassXHasClassY));
609 EXPECT_TRUE(
610 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
611 ZDescendantClassXHasClassY));
612 EXPECT_TRUE(notMatches(
613 "class Z {"
614 " class A {"
615 " class B {"
616 " class X {"
617 " class C {"
618 " class Y {};"
619 " };"
620 " };"
621 " }; "
622 " };"
623 "};", ZDescendantClassXHasClassY));
624
625 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000626 recordDecl(
627 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
628 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000629 hasName("Z"));
630 EXPECT_TRUE(
631 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
632 ZDescendantClassXDescendantClassY));
633 EXPECT_TRUE(matches(
634 "class Z {"
635 " class A {"
636 " class X {"
637 " class B {"
638 " class Y {};"
639 " };"
640 " class Y {};"
641 " };"
642 " };"
643 "};", ZDescendantClassXDescendantClassY));
644}
645
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000646// Implements a run method that returns whether BoundNodes contains a
647// Decl bound to Id that can be dynamically cast to T.
648// Optionally checks that the check succeeded a specific number of times.
649template <typename T>
650class VerifyIdIsBoundTo : public BoundNodesCallback {
651public:
652 // Create an object that checks that a node of type \c T was bound to \c Id.
653 // Does not check for a certain number of matches.
654 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
655 : Id(Id), ExpectedCount(-1), Count(0) {}
656
657 // Create an object that checks that a node of type \c T was bound to \c Id.
658 // Checks that there were exactly \c ExpectedCount matches.
659 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
660 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
661
662 // Create an object that checks that a node of type \c T was bound to \c Id.
663 // Checks that there was exactly one match with the name \c ExpectedName.
664 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000665 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
666 int ExpectedCount = 1)
667 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
668 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000669
Craig Toppera798a9d2014-03-02 09:32:10 +0000670 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000671 if (ExpectedCount != -1)
672 EXPECT_EQ(ExpectedCount, Count);
673 if (!ExpectedName.empty())
674 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000675 Count = 0;
676 Name.clear();
677 }
678
679 ~VerifyIdIsBoundTo() {
680 EXPECT_EQ(0, Count);
681 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000682 }
683
684 virtual bool run(const BoundNodes *Nodes) {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000685 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000686 if (Nodes->getNodeAs<T>(Id)) {
687 ++Count;
688 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
689 Name = Named->getNameAsString();
690 } else if (const NestedNameSpecifier *NNS =
691 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
692 llvm::raw_string_ostream OS(Name);
693 NNS->print(OS, PrintingPolicy(LangOptions()));
694 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000695 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
696 EXPECT_NE(M.end(), I);
697 if (I != M.end())
698 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000699 return true;
700 }
Craig Topper416fa342014-06-08 08:38:12 +0000701 EXPECT_TRUE(M.count(Id) == 0 ||
702 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000703 return false;
704 }
705
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000706 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
707 return run(Nodes);
708 }
709
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000710private:
711 const std::string Id;
712 const int ExpectedCount;
713 int Count;
714 const std::string ExpectedName;
715 std::string Name;
716};
717
718TEST(HasDescendant, MatchesDescendantTypes) {
719 EXPECT_TRUE(matches("void f() { int i = 3; }",
720 decl(hasDescendant(loc(builtinType())))));
721 EXPECT_TRUE(matches("void f() { int i = 3; }",
722 stmt(hasDescendant(builtinType()))));
723
724 EXPECT_TRUE(matches("void f() { int i = 3; }",
725 stmt(hasDescendant(loc(builtinType())))));
726 EXPECT_TRUE(matches("void f() { int i = 3; }",
727 stmt(hasDescendant(qualType(builtinType())))));
728
729 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
730 stmt(hasDescendant(isInteger()))));
731
732 EXPECT_TRUE(matchAndVerifyResultTrue(
733 "void f() { int a; float c; int d; int e; }",
734 functionDecl(forEachDescendant(
735 varDecl(hasDescendant(isInteger())).bind("x"))),
736 new VerifyIdIsBoundTo<Decl>("x", 3)));
737}
738
739TEST(HasDescendant, MatchesDescendantsOfTypes) {
740 EXPECT_TRUE(matches("void f() { int*** i; }",
741 qualType(hasDescendant(builtinType()))));
742 EXPECT_TRUE(matches("void f() { int*** i; }",
743 qualType(hasDescendant(
744 pointerType(pointee(builtinType()))))));
745 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000746 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000747
748 EXPECT_TRUE(matchAndVerifyResultTrue(
749 "void f() { int*** i; }",
750 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
751 new VerifyIdIsBoundTo<Type>("x", 2)));
752}
753
754TEST(Has, MatchesChildrenOfTypes) {
755 EXPECT_TRUE(matches("int i;",
756 varDecl(hasName("i"), has(isInteger()))));
757 EXPECT_TRUE(notMatches("int** i;",
758 varDecl(hasName("i"), has(isInteger()))));
759 EXPECT_TRUE(matchAndVerifyResultTrue(
760 "int (*f)(float, int);",
761 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
762 new VerifyIdIsBoundTo<QualType>("x", 2)));
763}
764
765TEST(Has, MatchesChildTypes) {
766 EXPECT_TRUE(matches(
767 "int* i;",
768 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
769 EXPECT_TRUE(notMatches(
770 "int* i;",
771 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
772}
773
Daniel Jasper1dad1832012-07-10 20:20:19 +0000774TEST(Enum, DoesNotMatchClasses) {
775 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
776}
777
778TEST(Enum, MatchesEnums) {
779 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
780}
781
782TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000783 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000784 EXPECT_TRUE(matches("enum X{ A };", Matcher));
785 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
786 EXPECT_TRUE(notMatches("enum X {};", Matcher));
787}
788
Manuel Klimek04616e42012-07-06 05:48:52 +0000789TEST(StatementMatcher, Has) {
790 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000791 expr(hasType(pointsTo(recordDecl(hasName("X")))),
792 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000793
794 EXPECT_TRUE(matches(
795 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
796 EXPECT_TRUE(notMatches(
797 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
798}
799
800TEST(StatementMatcher, HasDescendant) {
801 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000802 expr(hasType(pointsTo(recordDecl(hasName("X")))),
803 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000804
805 EXPECT_TRUE(matches(
806 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
807 HasDescendantVariableI));
808 EXPECT_TRUE(notMatches(
809 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
810 HasDescendantVariableI));
811}
812
813TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000814 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000815
816 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
817 EXPECT_TRUE(notMatches("class A {};", TypeA));
818
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000819 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000820
821 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
822 TypeDerivedFromA));
823 EXPECT_TRUE(notMatches("class A {};", TypeA));
824
825 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000826 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000827
828 EXPECT_TRUE(
829 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
830}
831
Manuel Klimek04616e42012-07-06 05:48:52 +0000832TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000833 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000834
835 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000836 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000837
838 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000839 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000840
841 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000842 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000843
844 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
845 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000846 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000847
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000848 StatementMatcher MethodX =
849 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000850
851 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
852 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000853 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000854}
855
856TEST(Matcher, BindTheSameNameInAlternatives) {
857 StatementMatcher matcher = anyOf(
858 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000859 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000860 hasRHS(integerLiteral(equals(0)))),
861 binaryOperator(hasOperatorName("+"),
862 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000863 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000864
865 EXPECT_TRUE(matchAndVerifyResultTrue(
866 // The first branch of the matcher binds x to 0 but then fails.
867 // The second branch binds x to f() and succeeds.
868 "int f() { return 0 + f(); }",
869 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000870 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000871}
872
Manuel Klimekfdf98762012-08-30 19:41:06 +0000873TEST(Matcher, BindsIDForMemoizedResults) {
874 // Using the same matcher in two match expressions will make memoization
875 // kick in.
876 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
877 EXPECT_TRUE(matchAndVerifyResultTrue(
878 "class A { class B { class X {}; }; };",
879 DeclarationMatcher(anyOf(
880 recordDecl(hasName("A"), hasDescendant(ClassX)),
881 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000882 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000883}
884
Daniel Jasper856194d02012-12-03 15:43:25 +0000885TEST(HasDeclaration, HasDeclarationOfEnumType) {
886 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
887 expr(hasType(pointsTo(
888 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
889}
890
Edwin Vaneed936452013-02-25 14:32:42 +0000891TEST(HasDeclaration, HasGetDeclTraitTest) {
892 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
893 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
894 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
895}
896
Edwin Vane2c197e02013-02-19 17:14:34 +0000897TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
898 EXPECT_TRUE(matches("typedef int X; X a;",
899 varDecl(hasName("a"),
900 hasType(typedefType(hasDeclaration(decl()))))));
901
902 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
903}
904
Edwin Vanef901b712013-02-25 14:49:29 +0000905TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
906 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
907 varDecl(hasType(templateSpecializationType(
908 hasDeclaration(namedDecl(hasName("A"))))))));
909}
910
Manuel Klimek04616e42012-07-06 05:48:52 +0000911TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000912 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000913 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000914 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000915 EXPECT_TRUE(
916 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000917 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000918 EXPECT_TRUE(
919 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000920 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000921}
922
923TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000924 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000925 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000926 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000927 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000928 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000929 EXPECT_TRUE(
930 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000931 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000932}
933
934TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000935 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000936 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000937 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000938 EXPECT_TRUE(
939 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000940 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000941}
942
943TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000944 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000945 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000946 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000947 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000948 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000949}
950
Manuel Klimekc16c6522013-06-20 13:08:29 +0000951TEST(HasTypeLoc, MatchesDeclaratorDecls) {
952 EXPECT_TRUE(matches("int x;",
953 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
954
955 // Make sure we don't crash on implicit constructors.
956 EXPECT_TRUE(notMatches("class X {}; X x;",
957 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
958}
959
Manuel Klimek04616e42012-07-06 05:48:52 +0000960TEST(Matcher, Call) {
961 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +0000962 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000963 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000964
965 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
966 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
967
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000968 StatementMatcher MethodOnY =
969 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000970
971 EXPECT_TRUE(
972 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
973 MethodOnY));
974 EXPECT_TRUE(
975 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
976 MethodOnY));
977 EXPECT_TRUE(
978 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
979 MethodOnY));
980 EXPECT_TRUE(
981 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
982 MethodOnY));
983 EXPECT_TRUE(
984 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
985 MethodOnY));
986
987 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000988 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000989
990 EXPECT_TRUE(
991 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
992 MethodOnYPointer));
993 EXPECT_TRUE(
994 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
995 MethodOnYPointer));
996 EXPECT_TRUE(
997 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
998 MethodOnYPointer));
999 EXPECT_TRUE(
1000 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1001 MethodOnYPointer));
1002 EXPECT_TRUE(
1003 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1004 MethodOnYPointer));
1005}
1006
Daniel Jasper5901e472012-10-01 13:40:41 +00001007TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001008 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001009 lambdaExpr()));
1010}
1011
1012TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001013 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1014 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001015 forRangeStmt()));
1016 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1017 forRangeStmt()));
1018}
1019
1020TEST(Matcher, UserDefinedLiteral) {
1021 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1022 " return i + 1;"
1023 "}"
1024 "char c = 'a'_inc;",
1025 userDefinedLiteral()));
1026}
1027
Daniel Jasper87c3d362012-09-20 14:12:57 +00001028TEST(Matcher, FlowControl) {
1029 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1030 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1031 continueStmt()));
1032 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1033 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1034 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1035}
1036
Daniel Jasper1dad1832012-07-10 20:20:19 +00001037TEST(HasType, MatchesAsString) {
1038 EXPECT_TRUE(
1039 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001040 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001041 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001042 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001043 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001044 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001045 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001046 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001047}
1048
Manuel Klimek04616e42012-07-06 05:48:52 +00001049TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001050 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001051 // Unary operator
1052 EXPECT_TRUE(matches("class Y { }; "
1053 "bool operator!(Y x) { return false; }; "
1054 "Y y; bool c = !y;", OpCall));
1055 // No match -- special operators like "new", "delete"
1056 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1057 // we need to figure out include paths in the test.
1058 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1059 // "class Y { }; "
1060 // "void *operator new(size_t size) { return 0; } "
1061 // "Y *y = new Y;", OpCall));
1062 EXPECT_TRUE(notMatches("class Y { }; "
1063 "void operator delete(void *p) { } "
1064 "void a() {Y *y = new Y; delete y;}", OpCall));
1065 // Binary operator
1066 EXPECT_TRUE(matches("class Y { }; "
1067 "bool operator&&(Y x, Y y) { return true; }; "
1068 "Y a; Y b; bool c = a && b;",
1069 OpCall));
1070 // No match -- normal operator, not an overloaded one.
1071 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1072 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1073}
1074
1075TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1076 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001077 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001078 EXPECT_TRUE(matches("class Y { }; "
1079 "bool operator&&(Y x, Y y) { return true; }; "
1080 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1081 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001082 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001083 EXPECT_TRUE(notMatches("class Y { }; "
1084 "bool operator&&(Y x, Y y) { return true; }; "
1085 "Y a; Y b; bool c = a && b;",
1086 OpCallLessLess));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001087 DeclarationMatcher ClassWithOpStar =
1088 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1089 EXPECT_TRUE(matches("class Y { int operator*(); };",
1090 ClassWithOpStar));
1091 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1092 ClassWithOpStar)) ;
Manuel Klimek04616e42012-07-06 05:48:52 +00001093}
1094
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001095TEST(Matcher, NestedOverloadedOperatorCalls) {
1096 EXPECT_TRUE(matchAndVerifyResultTrue(
1097 "class Y { }; "
1098 "Y& operator&&(Y& x, Y& y) { return x; }; "
1099 "Y a; Y b; Y c; Y d = a && b && c;",
1100 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1101 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1102 EXPECT_TRUE(matches(
1103 "class Y { }; "
1104 "Y& operator&&(Y& x, Y& y) { return x; }; "
1105 "Y a; Y b; Y c; Y d = a && b && c;",
1106 operatorCallExpr(hasParent(operatorCallExpr()))));
1107 EXPECT_TRUE(matches(
1108 "class Y { }; "
1109 "Y& operator&&(Y& x, Y& y) { return x; }; "
1110 "Y a; Y b; Y c; Y d = a && b && c;",
1111 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1112}
1113
Manuel Klimek04616e42012-07-06 05:48:52 +00001114TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001115 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001116 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001117
1118 EXPECT_TRUE(
1119 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1120 MethodOnY));
1121 EXPECT_TRUE(
1122 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1123 MethodOnY));
1124 EXPECT_TRUE(
1125 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1126 MethodOnY));
1127 EXPECT_TRUE(
1128 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1129 MethodOnY));
1130 EXPECT_TRUE(
1131 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1132 MethodOnY));
1133
1134 EXPECT_TRUE(matches(
1135 "class Y {"
1136 " public: virtual void x();"
1137 "};"
1138 "class X : public Y {"
1139 " public: virtual void x();"
1140 "};"
1141 "void z() { X *x; x->Y::x(); }", MethodOnY));
1142}
1143
1144TEST(Matcher, VariableUsage) {
1145 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001146 declRefExpr(to(
1147 varDecl(hasInitializer(
1148 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001149
1150 EXPECT_TRUE(matches(
1151 "class Y {"
1152 " public:"
1153 " bool x() const;"
1154 "};"
1155 "void z(const Y &y) {"
1156 " bool b = y.x();"
1157 " if (b) {}"
1158 "}", Reference));
1159
1160 EXPECT_TRUE(notMatches(
1161 "class Y {"
1162 " public:"
1163 " bool x() const;"
1164 "};"
1165 "void z(const Y &y) {"
1166 " bool b = y.x();"
1167 "}", Reference));
1168}
1169
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001170TEST(Matcher, VarDecl_Storage) {
1171 auto M = varDecl(hasName("X"), hasLocalStorage());
1172 EXPECT_TRUE(matches("void f() { int X; }", M));
1173 EXPECT_TRUE(notMatches("int X;", M));
1174 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1175
1176 M = varDecl(hasName("X"), hasGlobalStorage());
1177 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1178 EXPECT_TRUE(matches("int X;", M));
1179 EXPECT_TRUE(matches("void f() { static int X; }", M));
1180}
1181
Manuel Klimek61379422012-12-04 14:42:08 +00001182TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001183 EXPECT_TRUE(matches(
1184 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001185 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001186}
1187
Manuel Klimek04616e42012-07-06 05:48:52 +00001188TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001189 StatementMatcher CallOnVariableY =
1190 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001191
1192 EXPECT_TRUE(matches(
1193 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1194 EXPECT_TRUE(matches(
1195 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1196 EXPECT_TRUE(matches(
1197 "class Y { public: void x(); };"
1198 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1199 EXPECT_TRUE(matches(
1200 "class Y { public: void x(); };"
1201 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1202 EXPECT_TRUE(notMatches(
1203 "class Y { public: void x(); };"
1204 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1205 CallOnVariableY));
1206}
1207
Daniel Jasper1dad1832012-07-10 20:20:19 +00001208TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1209 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1210 unaryExprOrTypeTraitExpr()));
1211 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1212 alignOfExpr(anything())));
1213 // FIXME: Uncomment once alignof is enabled.
1214 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1215 // unaryExprOrTypeTraitExpr()));
1216 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1217 // sizeOfExpr()));
1218}
1219
1220TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1221 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1222 hasArgumentOfType(asString("int")))));
1223 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1224 hasArgumentOfType(asString("float")))));
1225 EXPECT_TRUE(matches(
1226 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001227 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001228 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001229 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001230}
1231
Manuel Klimek04616e42012-07-06 05:48:52 +00001232TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001233 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001234}
1235
1236TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001237 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001238}
1239
1240TEST(MemberExpression, MatchesVariable) {
1241 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001242 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001243 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001244 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001245 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001246 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001247}
1248
1249TEST(MemberExpression, MatchesStaticVariable) {
1250 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001251 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001252 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001253 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001254 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001255 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001256}
1257
Daniel Jasper4e566c42012-07-12 08:50:38 +00001258TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001259 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1260 EXPECT_TRUE(matches(
1261 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1262 callExpr(hasArgument(0, declRefExpr(
1263 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001264}
1265
1266TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001267 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001268 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001269 callExpr(hasArgument(0, declRefExpr(
1270 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001271}
1272
Manuel Klimek04616e42012-07-06 05:48:52 +00001273TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1274 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001275 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001276 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001277 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001278 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001279 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001280}
1281
1282TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1283 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001284 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001285 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001286 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001287 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001288 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001289}
1290
1291TEST(IsArrow, MatchesMemberCallsViaArrow) {
1292 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001293 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001294 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001295 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001296 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001297 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001298}
1299
1300TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001301 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001302
1303 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1304 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1305}
1306
1307TEST(Callee, MatchesMemberExpressions) {
1308 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001309 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001310 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001311 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001312}
1313
1314TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001315 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001316
1317 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1318 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1319
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001320 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1321 llvm::Triple::Win32) {
1322 // FIXME: Make this work for MSVC.
1323 // Dependent contexts, but a non-dependent call.
1324 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1325 CallFunctionF));
1326 EXPECT_TRUE(
1327 matches("void f(); template <int N> struct S { void g() { f(); } };",
1328 CallFunctionF));
1329 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001330
1331 // Depedent calls don't match.
1332 EXPECT_TRUE(
1333 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1334 CallFunctionF));
1335 EXPECT_TRUE(
1336 notMatches("void f(int);"
1337 "template <typename T> struct S { void g(T t) { f(t); } };",
1338 CallFunctionF));
1339}
1340
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001341TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1342 EXPECT_TRUE(
1343 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001344 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001345}
1346
1347TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1348 EXPECT_TRUE(
1349 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001350 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001351}
1352
1353TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1354 EXPECT_TRUE(
1355 notMatches("void g(); template <typename T> void f(T t) {}"
1356 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001357 functionTemplateDecl(hasName("f"),
1358 hasDescendant(declRefExpr(to(
1359 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001360}
1361
Manuel Klimek04616e42012-07-06 05:48:52 +00001362TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001363 StatementMatcher CallArgumentY = callExpr(
1364 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001365
1366 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1367 EXPECT_TRUE(
1368 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1369 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1370
Daniel Jasper848cbe12012-09-18 13:09:13 +00001371 StatementMatcher WrongIndex = callExpr(
1372 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001373 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1374}
1375
1376TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001377 StatementMatcher CallArgumentY = callExpr(
1378 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001379 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1380 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1381 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1382}
1383
1384TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001385 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001386
1387 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1388 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1389 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1390}
1391
Daniel Jasper9f501292012-12-04 11:54:27 +00001392TEST(Matcher, ParameterCount) {
1393 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1394 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1395 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1396 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1397 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1398}
1399
Manuel Klimek04616e42012-07-06 05:48:52 +00001400TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001401 DeclarationMatcher ReferenceClassX = varDecl(
1402 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001403 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1404 ReferenceClassX));
1405 EXPECT_TRUE(
1406 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001407 // The match here is on the implicit copy constructor code for
1408 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001409 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001410 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1411 EXPECT_TRUE(
1412 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001413 EXPECT_TRUE(
1414 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1415}
1416
Edwin Vane0a4836e2013-03-06 17:02:57 +00001417TEST(QualType, hasCanonicalType) {
1418 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1419 "int a;"
1420 "int_ref b = a;",
1421 varDecl(hasType(qualType(referenceType())))));
1422 EXPECT_TRUE(
1423 matches("typedef int &int_ref;"
1424 "int a;"
1425 "int_ref b = a;",
1426 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1427}
1428
Edwin Vane119d3df2013-04-02 18:15:55 +00001429TEST(QualType, hasLocalQualifiers) {
1430 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1431 varDecl(hasType(hasLocalQualifiers()))));
1432 EXPECT_TRUE(matches("int *const j = nullptr;",
1433 varDecl(hasType(hasLocalQualifiers()))));
1434 EXPECT_TRUE(matches("int *volatile k;",
1435 varDecl(hasType(hasLocalQualifiers()))));
1436 EXPECT_TRUE(notMatches("int m;",
1437 varDecl(hasType(hasLocalQualifiers()))));
1438}
1439
Manuel Klimek04616e42012-07-06 05:48:52 +00001440TEST(HasParameter, CallsInnerMatcher) {
1441 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001442 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001443 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001444 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001445}
1446
1447TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1448 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001449 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001450}
1451
1452TEST(HasType, MatchesParameterVariableTypesStrictly) {
1453 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001454 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001455 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001456 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001457 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001458 methodDecl(hasParameter(0,
1459 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001460 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001461 methodDecl(hasParameter(0,
1462 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001463}
1464
1465TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1466 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001467 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001468 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001469 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001470}
1471
Daniel Jasper1dad1832012-07-10 20:20:19 +00001472TEST(Returns, MatchesReturnTypes) {
1473 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001474 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001475 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001476 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001477 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001478 functionDecl(returns(hasDeclaration(
1479 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001480}
1481
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001482TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001483 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1484 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1485 functionDecl(isExternC())));
1486 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001487}
1488
Manuel Klimek04616e42012-07-06 05:48:52 +00001489TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1490 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001491 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001492}
1493
1494TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1495 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001496 methodDecl(hasAnyParameter(hasType(pointsTo(
1497 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001498}
1499
Alp Toker8db6e7a2014-01-05 06:38:57 +00001500TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001501 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001502 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001503 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001504 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001505}
1506
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001507TEST(Matcher, MatchesClassTemplateSpecialization) {
1508 EXPECT_TRUE(matches("template<typename T> struct A {};"
1509 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001510 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001511 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001512 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001513 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001514 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001515}
1516
Manuel Klimekc16c6522013-06-20 13:08:29 +00001517TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1518 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1519 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1520}
1521
1522TEST(ParmVarDecl, MatchesParmVars) {
1523 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1524 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1525}
1526
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001527TEST(Matcher, MatchesTypeTemplateArgument) {
1528 EXPECT_TRUE(matches(
1529 "template<typename T> struct B {};"
1530 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001531 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001532 asString("int"))))));
1533}
1534
1535TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1536 EXPECT_TRUE(matches(
1537 "struct B { int next; };"
1538 "template<int(B::*next_ptr)> struct A {};"
1539 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001540 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1541 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001542
1543 EXPECT_TRUE(notMatches(
1544 "template <typename T> struct A {};"
1545 "A<int> a;",
1546 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1547 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001548
1549 EXPECT_TRUE(matches(
1550 "struct B { int next; };"
1551 "template<int(B::*next_ptr)> struct A {};"
1552 "A<&B::next> a;",
1553 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1554 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1555
1556 EXPECT_TRUE(notMatches(
1557 "template <typename T> struct A {};"
1558 "A<int> a;",
1559 templateSpecializationType(hasAnyTemplateArgument(
1560 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001561}
1562
1563TEST(Matcher, MatchesSpecificArgument) {
1564 EXPECT_TRUE(matches(
1565 "template<typename T, typename U> class A {};"
1566 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001567 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001568 1, refersToType(asString("int"))))));
1569 EXPECT_TRUE(notMatches(
1570 "template<typename T, typename U> class A {};"
1571 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001572 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001573 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001574
1575 EXPECT_TRUE(matches(
1576 "template<typename T, typename U> class A {};"
1577 "A<bool, int> a;",
1578 templateSpecializationType(hasTemplateArgument(
1579 1, refersToType(asString("int"))))));
1580 EXPECT_TRUE(notMatches(
1581 "template<typename T, typename U> class A {};"
1582 "A<int, bool> a;",
1583 templateSpecializationType(hasTemplateArgument(
1584 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001585}
1586
Daniel Jasper639522c2013-02-25 12:02:08 +00001587TEST(Matcher, MatchesAccessSpecDecls) {
1588 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1589 EXPECT_TRUE(
1590 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1591 EXPECT_TRUE(
1592 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1593 EXPECT_TRUE(
1594 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1595
1596 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1597}
1598
Edwin Vane37ee1d72013-04-09 20:46:36 +00001599TEST(Matcher, MatchesVirtualMethod) {
1600 EXPECT_TRUE(matches("class X { virtual int f(); };",
1601 methodDecl(isVirtual(), hasName("::X::f"))));
1602 EXPECT_TRUE(notMatches("class X { int f(); };",
1603 methodDecl(isVirtual())));
1604}
1605
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001606TEST(Matcher, MatchesPureMethod) {
1607 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1608 methodDecl(isPure(), hasName("::X::f"))));
1609 EXPECT_TRUE(notMatches("class X { int f(); };",
1610 methodDecl(isPure())));
1611}
1612
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001613TEST(Matcher, MatchesConstMethod) {
1614 EXPECT_TRUE(matches("struct A { void foo() const; };",
1615 methodDecl(isConst())));
1616 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1617 methodDecl(isConst())));
1618}
1619
Edwin Vane37ee1d72013-04-09 20:46:36 +00001620TEST(Matcher, MatchesOverridingMethod) {
1621 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1622 "class Y : public X { int f(); };",
1623 methodDecl(isOverride(), hasName("::Y::f"))));
1624 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1625 "class Y : public X { int f(); };",
1626 methodDecl(isOverride(), hasName("::X::f"))));
1627 EXPECT_TRUE(notMatches("class X { int f(); }; "
1628 "class Y : public X { int f(); };",
1629 methodDecl(isOverride())));
1630 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1631 methodDecl(isOverride())));
1632}
1633
Manuel Klimek04616e42012-07-06 05:48:52 +00001634TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001635 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001636
1637 EXPECT_TRUE(
1638 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1639 EXPECT_TRUE(
1640 matches("class X { public: X(); }; void x() { X x = X(); }",
1641 Constructor));
1642 EXPECT_TRUE(
1643 matches("class X { public: X(int); }; void x() { X x = 0; }",
1644 Constructor));
1645 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1646}
1647
1648TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001649 StatementMatcher Constructor = constructExpr(
1650 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001651
1652 EXPECT_TRUE(
1653 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1654 Constructor));
1655 EXPECT_TRUE(
1656 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1657 Constructor));
1658 EXPECT_TRUE(
1659 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1660 Constructor));
1661 EXPECT_TRUE(
1662 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1663 Constructor));
1664
Daniel Jasper848cbe12012-09-18 13:09:13 +00001665 StatementMatcher WrongIndex = constructExpr(
1666 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001667 EXPECT_TRUE(
1668 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1669 WrongIndex));
1670}
1671
1672TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001673 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001674
1675 EXPECT_TRUE(
1676 matches("class X { public: X(int); }; void x() { X x(0); }",
1677 Constructor1Arg));
1678 EXPECT_TRUE(
1679 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1680 Constructor1Arg));
1681 EXPECT_TRUE(
1682 matches("class X { public: X(int); }; void x() { X x = 0; }",
1683 Constructor1Arg));
1684 EXPECT_TRUE(
1685 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1686 Constructor1Arg));
1687}
1688
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001689TEST(Matcher, ConstructorListInitialization) {
1690 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1691
1692 EXPECT_TRUE(
1693 matches("class X { public: X(int); }; void x() { X x{0}; }",
1694 ConstructorListInit));
1695 EXPECT_FALSE(
1696 matches("class X { public: X(int); }; void x() { X x(0); }",
1697 ConstructorListInit));
1698}
1699
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001700TEST(Matcher,ThisExpr) {
1701 EXPECT_TRUE(
1702 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1703 EXPECT_TRUE(
1704 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1705}
1706
Manuel Klimek04616e42012-07-06 05:48:52 +00001707TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001708 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001709
1710 std::string ClassString = "class string { public: string(); ~string(); }; ";
1711
1712 EXPECT_TRUE(
1713 matches(ClassString +
1714 "string GetStringByValue();"
1715 "void FunctionTakesString(string s);"
1716 "void run() { FunctionTakesString(GetStringByValue()); }",
1717 TempExpression));
1718
1719 EXPECT_TRUE(
1720 notMatches(ClassString +
1721 "string* GetStringPointer(); "
1722 "void FunctionTakesStringPtr(string* s);"
1723 "void run() {"
1724 " string* s = GetStringPointer();"
1725 " FunctionTakesStringPtr(GetStringPointer());"
1726 " FunctionTakesStringPtr(s);"
1727 "}",
1728 TempExpression));
1729
1730 EXPECT_TRUE(
1731 notMatches("class no_dtor {};"
1732 "no_dtor GetObjByValue();"
1733 "void ConsumeObj(no_dtor param);"
1734 "void run() { ConsumeObj(GetObjByValue()); }",
1735 TempExpression));
1736}
1737
Sam Panzer68a35af2012-08-24 22:04:44 +00001738TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1739 std::string ClassString =
1740 "class string { public: string(); int length(); }; ";
1741
1742 EXPECT_TRUE(
1743 matches(ClassString +
1744 "string GetStringByValue();"
1745 "void FunctionTakesString(string s);"
1746 "void run() { FunctionTakesString(GetStringByValue()); }",
1747 materializeTemporaryExpr()));
1748
1749 EXPECT_TRUE(
1750 notMatches(ClassString +
1751 "string* GetStringPointer(); "
1752 "void FunctionTakesStringPtr(string* s);"
1753 "void run() {"
1754 " string* s = GetStringPointer();"
1755 " FunctionTakesStringPtr(GetStringPointer());"
1756 " FunctionTakesStringPtr(s);"
1757 "}",
1758 materializeTemporaryExpr()));
1759
1760 EXPECT_TRUE(
1761 notMatches(ClassString +
1762 "string GetStringByValue();"
1763 "void run() { int k = GetStringByValue().length(); }",
1764 materializeTemporaryExpr()));
1765
1766 EXPECT_TRUE(
1767 notMatches(ClassString +
1768 "string GetStringByValue();"
1769 "void run() { GetStringByValue(); }",
1770 materializeTemporaryExpr()));
1771}
1772
Manuel Klimek04616e42012-07-06 05:48:52 +00001773TEST(ConstructorDeclaration, SimpleCase) {
1774 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001775 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001776 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001777 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001778}
1779
1780TEST(ConstructorDeclaration, IsImplicit) {
1781 // This one doesn't match because the constructor is not added by the
1782 // compiler (it is not needed).
1783 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001784 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001785 // The compiler added the implicit default constructor.
1786 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001787 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001788 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001789 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001790 // The compiler added an implicit assignment operator.
1791 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1792 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001793}
1794
Daniel Jasper1dad1832012-07-10 20:20:19 +00001795TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1796 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001797 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001798}
1799
1800TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001801 EXPECT_TRUE(notMatches("class Foo {};",
1802 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001803}
1804
Manuel Klimek04616e42012-07-06 05:48:52 +00001805TEST(HasAnyConstructorInitializer, SimpleCase) {
1806 EXPECT_TRUE(notMatches(
1807 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001808 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001809 EXPECT_TRUE(matches(
1810 "class Foo {"
1811 " Foo() : foo_() { }"
1812 " int foo_;"
1813 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001814 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001815}
1816
1817TEST(HasAnyConstructorInitializer, ForField) {
1818 static const char Code[] =
1819 "class Baz { };"
1820 "class Foo {"
1821 " Foo() : foo_() { }"
1822 " Baz foo_;"
1823 " Baz bar_;"
1824 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001825 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1826 forField(hasType(recordDecl(hasName("Baz"))))))));
1827 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001828 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001829 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1830 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001831}
1832
1833TEST(HasAnyConstructorInitializer, WithInitializer) {
1834 static const char Code[] =
1835 "class Foo {"
1836 " Foo() : foo_(0) { }"
1837 " int foo_;"
1838 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001839 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001840 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001841 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001842 withInitializer(integerLiteral(equals(1)))))));
1843}
1844
1845TEST(HasAnyConstructorInitializer, IsWritten) {
1846 static const char Code[] =
1847 "struct Bar { Bar(){} };"
1848 "class Foo {"
1849 " Foo() : foo_() { }"
1850 " Bar foo_;"
1851 " Bar bar_;"
1852 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001853 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001854 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001855 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001856 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001857 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001858 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1859}
1860
1861TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001862 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001863
1864 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
1865 EXPECT_TRUE(
1866 matches("class X { public: X(); }; void x() { new X(); }", New));
1867 EXPECT_TRUE(
1868 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1869 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
1870}
1871
1872TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001873 StatementMatcher New = constructExpr(
1874 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001875
1876 EXPECT_TRUE(
1877 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1878 New));
1879 EXPECT_TRUE(
1880 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1881 New));
1882 EXPECT_TRUE(
1883 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
1884 New));
1885
Daniel Jasper848cbe12012-09-18 13:09:13 +00001886 StatementMatcher WrongIndex = constructExpr(
1887 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001888 EXPECT_TRUE(
1889 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
1890 WrongIndex));
1891}
1892
1893TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001894 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001895
1896 EXPECT_TRUE(
1897 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1898 EXPECT_TRUE(
1899 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
1900 New));
1901}
1902
Daniel Jasper1dad1832012-07-10 20:20:19 +00001903TEST(Matcher, DeleteExpression) {
1904 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001905 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001906}
1907
Manuel Klimek04616e42012-07-06 05:48:52 +00001908TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001909 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001910
1911 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
1912 EXPECT_TRUE(
1913 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
1914 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
1915}
1916
1917TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001918 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001919 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
1920 // wide string
1921 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
1922 // with escaped characters
1923 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
1924 // no matching -- though the data type is the same, there is no string literal
1925 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
1926}
1927
1928TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001929 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001930 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
1931 // wide character
1932 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
1933 // wide character, Hex encoded, NOT MATCHED!
1934 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
1935 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
1936}
1937
1938TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001939 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00001940 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
1941 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
1942 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
1943 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
1944
1945 // Non-matching cases (character literals, float and double)
1946 EXPECT_TRUE(notMatches("int i = L'a';",
1947 HasIntLiteral)); // this is actually a character
1948 // literal cast to int
1949 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
1950 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
1951 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
1952}
1953
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00001954TEST(Matcher, FloatLiterals) {
1955 StatementMatcher HasFloatLiteral = floatLiteral();
1956 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
1957 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
1958 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
1959 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
1960 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
1961
1962 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
1963}
1964
Daniel Jasper5901e472012-10-01 13:40:41 +00001965TEST(Matcher, NullPtrLiteral) {
1966 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
1967}
1968
Daniel Jasper87c3d362012-09-20 14:12:57 +00001969TEST(Matcher, AsmStatement) {
1970 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1971}
1972
Manuel Klimek04616e42012-07-06 05:48:52 +00001973TEST(Matcher, Conditions) {
1974 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
1975
1976 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
1977 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
1978 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
1979 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
1980 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
1981}
1982
Manuel Klimek909b5c942014-05-27 10:04:12 +00001983TEST(IfStmt, ChildTraversalMatchers) {
1984 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
1985 ifStmt(hasThen(boolLiteral(equals(true))))));
1986 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
1987 ifStmt(hasThen(boolLiteral(equals(true))))));
1988 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
1989 ifStmt(hasElse(boolLiteral(equals(true))))));
1990 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
1991 ifStmt(hasElse(boolLiteral(equals(true))))));
1992}
1993
Manuel Klimek04616e42012-07-06 05:48:52 +00001994TEST(MatchBinaryOperator, HasOperatorName) {
1995 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
1996
1997 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
1998 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
1999}
2000
2001TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2002 StatementMatcher OperatorTrueFalse =
2003 binaryOperator(hasLHS(boolLiteral(equals(true))),
2004 hasRHS(boolLiteral(equals(false))));
2005
2006 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2007 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2008 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2009}
2010
2011TEST(MatchBinaryOperator, HasEitherOperand) {
2012 StatementMatcher HasOperand =
2013 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2014
2015 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2016 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2017 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2018}
2019
2020TEST(Matcher, BinaryOperatorTypes) {
2021 // Integration test that verifies the AST provides all binary operators in
2022 // a way we expect.
2023 // FIXME: Operator ','
2024 EXPECT_TRUE(
2025 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2026 EXPECT_TRUE(
2027 matches("bool b; bool c = (b = true);",
2028 binaryOperator(hasOperatorName("="))));
2029 EXPECT_TRUE(
2030 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2031 EXPECT_TRUE(
2032 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2033 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2034 EXPECT_TRUE(
2035 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2036 EXPECT_TRUE(
2037 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2038 EXPECT_TRUE(
2039 matches("int i = 1; int j = (i <<= 2);",
2040 binaryOperator(hasOperatorName("<<="))));
2041 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2042 EXPECT_TRUE(
2043 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2044 EXPECT_TRUE(
2045 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2046 EXPECT_TRUE(
2047 matches("int i = 1; int j = (i >>= 2);",
2048 binaryOperator(hasOperatorName(">>="))));
2049 EXPECT_TRUE(
2050 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2051 EXPECT_TRUE(
2052 matches("int i = 42; int j = (i ^= 42);",
2053 binaryOperator(hasOperatorName("^="))));
2054 EXPECT_TRUE(
2055 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2056 EXPECT_TRUE(
2057 matches("int i = 42; int j = (i %= 42);",
2058 binaryOperator(hasOperatorName("%="))));
2059 EXPECT_TRUE(
2060 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2061 EXPECT_TRUE(
2062 matches("bool b = true && false;",
2063 binaryOperator(hasOperatorName("&&"))));
2064 EXPECT_TRUE(
2065 matches("bool b = true; bool c = (b &= false);",
2066 binaryOperator(hasOperatorName("&="))));
2067 EXPECT_TRUE(
2068 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2069 EXPECT_TRUE(
2070 matches("bool b = true || false;",
2071 binaryOperator(hasOperatorName("||"))));
2072 EXPECT_TRUE(
2073 matches("bool b = true; bool c = (b |= false);",
2074 binaryOperator(hasOperatorName("|="))));
2075 EXPECT_TRUE(
2076 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2077 EXPECT_TRUE(
2078 matches("int i = 42; int j = (i *= 23);",
2079 binaryOperator(hasOperatorName("*="))));
2080 EXPECT_TRUE(
2081 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2082 EXPECT_TRUE(
2083 matches("int i = 42; int j = (i /= 23);",
2084 binaryOperator(hasOperatorName("/="))));
2085 EXPECT_TRUE(
2086 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2087 EXPECT_TRUE(
2088 matches("int i = 42; int j = (i += 23);",
2089 binaryOperator(hasOperatorName("+="))));
2090 EXPECT_TRUE(
2091 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2092 EXPECT_TRUE(
2093 matches("int i = 42; int j = (i -= 23);",
2094 binaryOperator(hasOperatorName("-="))));
2095 EXPECT_TRUE(
2096 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2097 binaryOperator(hasOperatorName("->*"))));
2098 EXPECT_TRUE(
2099 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2100 binaryOperator(hasOperatorName(".*"))));
2101
2102 // Member expressions as operators are not supported in matches.
2103 EXPECT_TRUE(
2104 notMatches("struct A { void x(A *a) { a->x(this); } };",
2105 binaryOperator(hasOperatorName("->"))));
2106
2107 // Initializer assignments are not represented as operator equals.
2108 EXPECT_TRUE(
2109 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2110
2111 // Array indexing is not represented as operator.
2112 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2113
2114 // Overloaded operators do not match at all.
2115 EXPECT_TRUE(notMatches(
2116 "struct A { bool operator&&(const A &a) const { return false; } };"
2117 "void x() { A a, b; a && b; }",
2118 binaryOperator()));
2119}
2120
2121TEST(MatchUnaryOperator, HasOperatorName) {
2122 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2123
2124 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2125 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2126}
2127
2128TEST(MatchUnaryOperator, HasUnaryOperand) {
2129 StatementMatcher OperatorOnFalse =
2130 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2131
2132 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2133 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2134}
2135
2136TEST(Matcher, UnaryOperatorTypes) {
2137 // Integration test that verifies the AST provides all unary operators in
2138 // a way we expect.
2139 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2140 EXPECT_TRUE(
2141 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2142 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2143 EXPECT_TRUE(
2144 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2145 EXPECT_TRUE(
2146 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2147 EXPECT_TRUE(
2148 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2149 EXPECT_TRUE(
2150 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2151 EXPECT_TRUE(
2152 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2153 EXPECT_TRUE(
2154 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2155 EXPECT_TRUE(
2156 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2157
2158 // We don't match conversion operators.
2159 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2160
2161 // Function calls are not represented as operator.
2162 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2163
2164 // Overloaded operators do not match at all.
2165 // FIXME: We probably want to add that.
2166 EXPECT_TRUE(notMatches(
2167 "struct A { bool operator!() const { return false; } };"
2168 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2169}
2170
2171TEST(Matcher, ConditionalOperator) {
2172 StatementMatcher Conditional = conditionalOperator(
2173 hasCondition(boolLiteral(equals(true))),
2174 hasTrueExpression(boolLiteral(equals(false))));
2175
2176 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2177 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2178 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2179
2180 StatementMatcher ConditionalFalse = conditionalOperator(
2181 hasFalseExpression(boolLiteral(equals(false))));
2182
2183 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2184 EXPECT_TRUE(
2185 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2186}
2187
Daniel Jasper1dad1832012-07-10 20:20:19 +00002188TEST(ArraySubscriptMatchers, ArraySubscripts) {
2189 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2190 arraySubscriptExpr()));
2191 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2192 arraySubscriptExpr()));
2193}
2194
2195TEST(ArraySubscriptMatchers, ArrayIndex) {
2196 EXPECT_TRUE(matches(
2197 "int i[2]; void f() { i[1] = 1; }",
2198 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2199 EXPECT_TRUE(matches(
2200 "int i[2]; void f() { 1[i] = 1; }",
2201 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2202 EXPECT_TRUE(notMatches(
2203 "int i[2]; void f() { i[1] = 1; }",
2204 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2205}
2206
2207TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2208 EXPECT_TRUE(matches(
2209 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002210 arraySubscriptExpr(hasBase(implicitCastExpr(
2211 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002212}
2213
Manuel Klimek04616e42012-07-06 05:48:52 +00002214TEST(Matcher, HasNameSupportsNamespaces) {
2215 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002216 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002217 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002218 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002219 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002220 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002221 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002222 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002223 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002224 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002225 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002226 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002227 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002228 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002229 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002230 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002231 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002232 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002233 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002234 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002235 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002236 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002237 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002238 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002239}
2240
2241TEST(Matcher, HasNameSupportsOuterClasses) {
2242 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002243 matches("class A { class B { class C; }; };",
2244 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002245 EXPECT_TRUE(
2246 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002247 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002248 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002249 matches("class A { class B { class C; }; };",
2250 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002251 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002252 matches("class A { class B { class C; }; };",
2253 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002254 EXPECT_TRUE(
2255 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002256 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002257 EXPECT_TRUE(
2258 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002259 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002260 EXPECT_TRUE(
2261 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002262 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002263 EXPECT_TRUE(
2264 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002265 recordDecl(hasName("::C"))));
2266 EXPECT_TRUE(
2267 notMatches("class A { class B { class C; }; };",
2268 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002269 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002270 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002271 EXPECT_TRUE(
2272 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002273 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002274}
2275
2276TEST(Matcher, IsDefinition) {
2277 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002278 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002279 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2280 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2281
2282 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002283 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002284 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2285 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2286
2287 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002288 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002289 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2290 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2291}
2292
2293TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002294 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002295 ofClass(hasName("X")))));
2296
2297 EXPECT_TRUE(
2298 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2299 EXPECT_TRUE(
2300 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2301 Constructor));
2302 EXPECT_TRUE(
2303 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2304 Constructor));
2305}
2306
2307TEST(Matcher, VisitsTemplateInstantiations) {
2308 EXPECT_TRUE(matches(
2309 "class A { public: void x(); };"
2310 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002311 "void f() { B<A> b; b.y(); }",
2312 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002313
2314 EXPECT_TRUE(matches(
2315 "class A { public: void x(); };"
2316 "class C {"
2317 " public:"
2318 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2319 "};"
2320 "void f() {"
2321 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002322 "}",
2323 recordDecl(hasName("C"),
2324 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002325}
2326
Daniel Jasper1dad1832012-07-10 20:20:19 +00002327TEST(Matcher, HandlesNullQualTypes) {
2328 // FIXME: Add a Type matcher so we can replace uses of this
2329 // variable with Type(True())
2330 const TypeMatcher AnyType = anything();
2331
2332 // We don't really care whether this matcher succeeds; we're testing that
2333 // it completes without crashing.
2334 EXPECT_TRUE(matches(
2335 "struct A { };"
2336 "template <typename T>"
2337 "void f(T t) {"
2338 " T local_t(t /* this becomes a null QualType in the AST */);"
2339 "}"
2340 "void g() {"
2341 " f(0);"
2342 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002343 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002344 anyOf(
2345 TypeMatcher(hasDeclaration(anything())),
2346 pointsTo(AnyType),
2347 references(AnyType)
2348 // Other QualType matchers should go here.
2349 ))))));
2350}
2351
Manuel Klimek04616e42012-07-06 05:48:52 +00002352// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002353AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002354 // Make sure all special variables are used: node, match_finder,
2355 // bound_nodes_builder, and the parameter named 'AMatcher'.
2356 return AMatcher.matches(Node, Finder, Builder);
2357}
2358
2359TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002360 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002361
2362 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002363 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002364
2365 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002366 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002367
2368 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002369 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002370}
2371
2372AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +00002373 polymorphicHas,
2374 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2375 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002376 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002377 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002378 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2379 ASTMatchFinder::BK_First);
2380}
2381
2382TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002383 DeclarationMatcher HasClassB =
2384 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002385
2386 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002387 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002388
2389 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002390 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002391
2392 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002393 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002394
2395 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002396 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002397
2398 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2399}
2400
2401TEST(For, FindsForLoops) {
2402 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2403 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002404 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2405 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002406 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002407}
2408
Daniel Jasper4e566c42012-07-12 08:50:38 +00002409TEST(For, ForLoopInternals) {
2410 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2411 forStmt(hasCondition(anything()))));
2412 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2413 forStmt(hasLoopInit(anything()))));
2414}
2415
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002416TEST(For, ForRangeLoopInternals) {
2417 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2418 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002419 EXPECT_TRUE(matches(
2420 "void f(){ int a[] {1, 2}; for (int i : a); }",
2421 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002422}
2423
Daniel Jasper4e566c42012-07-12 08:50:38 +00002424TEST(For, NegativeForLoopInternals) {
2425 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002426 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002427 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2428 forStmt(hasLoopInit(anything()))));
2429}
2430
Manuel Klimek04616e42012-07-06 05:48:52 +00002431TEST(For, ReportsNoFalsePositives) {
2432 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2433 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2434}
2435
2436TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002437 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2438 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2439 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002440}
2441
2442TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2443 // It's not a compound statement just because there's "{}" in the source
2444 // text. This is an AST search, not grep.
2445 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002446 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002447 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002448 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002449}
2450
Daniel Jasper4e566c42012-07-12 08:50:38 +00002451TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002452 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002453 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002454 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002455 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002456 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002457 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002458 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002459 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002460 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2461 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002462}
2463
2464TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2465 // The simplest case: every compound statement is in a function
2466 // definition, and the function body itself must be a compound
2467 // statement.
2468 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002469 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002470}
2471
2472TEST(HasAnySubstatement, IsNotRecursive) {
2473 // It's really "has any immediate substatement".
2474 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002475 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002476}
2477
2478TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2479 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002480 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002481}
2482
2483TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2484 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002485 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002486}
2487
2488TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2489 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002490 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002491 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002492 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002493}
2494
2495TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2496 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002497 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002498 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002499 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002500 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002501 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002502}
2503
2504TEST(StatementCountIs, WorksWithMultipleStatements) {
2505 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002506 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002507}
2508
2509TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2510 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002511 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002512 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002513 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002514 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002515 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002516 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002517 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002518}
2519
2520TEST(Member, WorksInSimplestCase) {
2521 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002522 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002523}
2524
2525TEST(Member, DoesNotMatchTheBaseExpression) {
2526 // Don't pick out the wrong part of the member expression, this should
2527 // be checking the member (name) only.
2528 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002529 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002530}
2531
2532TEST(Member, MatchesInMemberFunctionCall) {
2533 EXPECT_TRUE(matches("void f() {"
2534 " struct { void first() {}; } s;"
2535 " s.first();"
2536 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002537 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002538}
2539
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002540TEST(Member, MatchesMember) {
2541 EXPECT_TRUE(matches(
2542 "struct A { int i; }; void f() { A a; a.i = 2; }",
2543 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2544 EXPECT_TRUE(notMatches(
2545 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2546 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2547}
2548
Daniel Jasper639522c2013-02-25 12:02:08 +00002549TEST(Member, UnderstandsAccess) {
2550 EXPECT_TRUE(matches(
2551 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2552 EXPECT_TRUE(notMatches(
2553 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2554 EXPECT_TRUE(notMatches(
2555 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2556
2557 EXPECT_TRUE(notMatches(
2558 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2559 EXPECT_TRUE(notMatches(
2560 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2561 EXPECT_TRUE(matches(
2562 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2563
2564 EXPECT_TRUE(notMatches(
2565 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2566 EXPECT_TRUE(matches("class A { protected: int i; };",
2567 fieldDecl(isProtected(), hasName("i"))));
2568 EXPECT_TRUE(notMatches(
2569 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2570
2571 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2572 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2573 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2574 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2575}
2576
Dmitri Gribenko06963042012-08-18 00:29:27 +00002577TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002578 // Fails in C++11 mode
2579 EXPECT_TRUE(matchesConditionally(
2580 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2581 "class X { void *operator new(std::size_t); };",
2582 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002583
2584 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002585 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002586
Daniel Jasper5901e472012-10-01 13:40:41 +00002587 // Fails in C++11 mode
2588 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002589 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2590 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002591 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002592}
2593
Manuel Klimek04616e42012-07-06 05:48:52 +00002594TEST(HasObjectExpression, DoesNotMatchMember) {
2595 EXPECT_TRUE(notMatches(
2596 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002597 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002598}
2599
2600TEST(HasObjectExpression, MatchesBaseOfVariable) {
2601 EXPECT_TRUE(matches(
2602 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002603 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002604 EXPECT_TRUE(matches(
2605 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002606 memberExpr(hasObjectExpression(
2607 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002608}
2609
2610TEST(HasObjectExpression,
2611 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2612 EXPECT_TRUE(matches(
2613 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002614 memberExpr(hasObjectExpression(
2615 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002616 EXPECT_TRUE(matches(
2617 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002618 memberExpr(hasObjectExpression(
2619 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002620}
2621
2622TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002623 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2624 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2625 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2626 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002627}
2628
2629TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002630 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002631}
2632
2633TEST(IsConstQualified, MatchesConstInt) {
2634 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002635 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002636}
2637
2638TEST(IsConstQualified, MatchesConstPointer) {
2639 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002640 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002641}
2642
2643TEST(IsConstQualified, MatchesThroughTypedef) {
2644 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002645 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002646 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002647 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002648}
2649
2650TEST(IsConstQualified, DoesNotMatchInappropriately) {
2651 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002652 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002653 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002654 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002655}
2656
Sam Panzer80c13772012-08-16 16:58:10 +00002657TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002658 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2659 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2660 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2661 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002662}
2663TEST(CastExpression, MatchesImplicitCasts) {
2664 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002665 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002666 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002667 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002668}
2669
2670TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002671 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2672 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2673 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2674 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002675}
2676
Manuel Klimek04616e42012-07-06 05:48:52 +00002677TEST(ReinterpretCast, MatchesSimpleCase) {
2678 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002679 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002680}
2681
2682TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002683 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002684 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002685 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002686 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002687 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002688 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2689 "B b;"
2690 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002691 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002692}
2693
2694TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002695 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002696 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002697 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002698}
2699
2700TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002701 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002702 EXPECT_TRUE(
2703 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002704 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002705 EXPECT_TRUE(
2706 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002707 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002708}
2709
2710TEST(DynamicCast, MatchesSimpleCase) {
2711 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2712 "B b;"
2713 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002714 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002715}
2716
2717TEST(StaticCast, MatchesSimpleCase) {
2718 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002719 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002720}
2721
2722TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002723 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002724 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002725 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002726 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002727 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002728 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2729 "B b;"
2730 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002731 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002732}
2733
Daniel Jasper417f7762012-09-18 13:36:17 +00002734TEST(CStyleCast, MatchesSimpleCase) {
2735 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2736}
2737
2738TEST(CStyleCast, DoesNotMatchOtherCasts) {
2739 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2740 "char q, *r = const_cast<char*>(&q);"
2741 "void* s = reinterpret_cast<char*>(&s);"
2742 "struct B { virtual ~B() {} }; struct D : B {};"
2743 "B b;"
2744 "D* t = dynamic_cast<D*>(&b);",
2745 cStyleCastExpr()));
2746}
2747
Manuel Klimek04616e42012-07-06 05:48:52 +00002748TEST(HasDestinationType, MatchesSimpleCase) {
2749 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002750 staticCastExpr(hasDestinationType(
2751 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002752}
2753
Sam Panzer80c13772012-08-16 16:58:10 +00002754TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2755 // This test creates an implicit const cast.
2756 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002757 implicitCastExpr(
2758 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002759 // This test creates an implicit array-to-pointer cast.
2760 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002761 implicitCastExpr(hasImplicitDestinationType(
2762 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002763}
2764
2765TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2766 // This test creates an implicit cast from int to char.
2767 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002768 implicitCastExpr(hasImplicitDestinationType(
2769 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002770 // This test creates an implicit array-to-pointer cast.
2771 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002772 implicitCastExpr(hasImplicitDestinationType(
2773 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002774}
2775
2776TEST(ImplicitCast, MatchesSimpleCase) {
2777 // This test creates an implicit const cast.
2778 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002779 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002780 // This test creates an implicit cast from int to char.
2781 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002782 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002783 // This test creates an implicit array-to-pointer cast.
2784 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002785 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002786}
2787
2788TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002789 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002790 // are present, and that it ignores explicit and paren casts.
2791
2792 // These two test cases have no casts.
2793 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002794 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002795 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002796 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002797
2798 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002799 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002800 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002801 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002802
2803 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002804 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002805}
2806
2807TEST(IgnoringImpCasts, MatchesImpCasts) {
2808 // This test checks that ignoringImpCasts matches when implicit casts are
2809 // present and its inner matcher alone does not match.
2810 // Note that this test creates an implicit const cast.
2811 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002812 varDecl(hasInitializer(ignoringImpCasts(
2813 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002814 // This test creates an implict cast from int to char.
2815 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002816 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002817 integerLiteral(equals(0)))))));
2818}
2819
2820TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2821 // These tests verify that ignoringImpCasts does not match if the inner
2822 // matcher does not match.
2823 // Note that the first test creates an implicit const cast.
2824 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002825 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002826 unless(anything()))))));
2827 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002828 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002829 unless(anything()))))));
2830
2831 // These tests verify that ignoringImplictCasts does not look through explicit
2832 // casts or parentheses.
2833 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002834 varDecl(hasInitializer(ignoringImpCasts(
2835 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002836 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002837 varDecl(hasInitializer(ignoringImpCasts(
2838 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002839 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002840 varDecl(hasInitializer(ignoringImpCasts(
2841 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002842 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002843 varDecl(hasInitializer(ignoringImpCasts(
2844 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002845}
2846
2847TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2848 // This test verifies that expressions that do not have implicit casts
2849 // still match the inner matcher.
2850 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002851 varDecl(hasInitializer(ignoringImpCasts(
2852 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002853}
2854
2855TEST(IgnoringParenCasts, MatchesParenCasts) {
2856 // This test checks that ignoringParenCasts matches when parentheses and/or
2857 // casts are present and its inner matcher alone does not match.
2858 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002859 varDecl(hasInitializer(ignoringParenCasts(
2860 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002861 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002862 varDecl(hasInitializer(ignoringParenCasts(
2863 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002864
2865 // This test creates an implict cast from int to char in addition to the
2866 // parentheses.
2867 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002868 varDecl(hasInitializer(ignoringParenCasts(
2869 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002870
2871 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002872 varDecl(hasInitializer(ignoringParenCasts(
2873 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002874 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002875 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002876 integerLiteral(equals(0)))))));
2877}
2878
2879TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
2880 // This test verifies that expressions that do not have any casts still match.
2881 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002882 varDecl(hasInitializer(ignoringParenCasts(
2883 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002884}
2885
2886TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
2887 // These tests verify that ignoringImpCasts does not match if the inner
2888 // matcher does not match.
2889 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002890 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002891 unless(anything()))))));
2892
2893 // This test creates an implicit cast from int to char in addition to the
2894 // parentheses.
2895 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002896 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002897 unless(anything()))))));
2898
2899 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002900 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002901 unless(anything()))))));
2902}
2903
2904TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
2905 // This test checks that ignoringParenAndImpCasts matches when
2906 // parentheses and/or implicit casts are present and its inner matcher alone
2907 // does not match.
2908 // Note that this test creates an implicit const cast.
2909 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002910 varDecl(hasInitializer(ignoringParenImpCasts(
2911 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002912 // This test creates an implicit cast from int to char.
2913 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002914 varDecl(hasInitializer(ignoringParenImpCasts(
2915 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002916}
2917
2918TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
2919 // This test verifies that expressions that do not have parentheses or
2920 // implicit casts still match.
2921 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002922 varDecl(hasInitializer(ignoringParenImpCasts(
2923 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002924 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002925 varDecl(hasInitializer(ignoringParenImpCasts(
2926 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002927}
2928
2929TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
2930 // These tests verify that ignoringParenImpCasts does not match if
2931 // the inner matcher does not match.
2932 // This test creates an implicit cast.
2933 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002934 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002935 unless(anything()))))));
2936 // These tests verify that ignoringParenAndImplictCasts does not look
2937 // through explicit casts.
2938 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002939 varDecl(hasInitializer(ignoringParenImpCasts(
2940 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002941 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002942 varDecl(hasInitializer(ignoringParenImpCasts(
2943 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002944 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002945 varDecl(hasInitializer(ignoringParenImpCasts(
2946 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002947}
2948
Manuel Klimeke9235692012-07-25 10:02:02 +00002949TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002950 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
2951 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002952 implicitCastExpr(
2953 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002954}
2955
Manuel Klimeke9235692012-07-25 10:02:02 +00002956TEST(HasSourceExpression, MatchesExplicitCasts) {
2957 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002958 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002959 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002960 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00002961}
2962
Manuel Klimek04616e42012-07-06 05:48:52 +00002963TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002964 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002965}
2966
2967TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002968 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002969}
2970
2971TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002972 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002973}
2974
2975TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002976 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002977}
2978
Samuel Benzaquenf1066292014-04-02 13:12:14 +00002979TEST(ExprWithCleanups, MatchesExprWithCleanups) {
2980 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
2981 "const Foo f = Foo();",
2982 varDecl(hasInitializer(exprWithCleanups()))));
2983 EXPECT_FALSE(matches("struct Foo { };"
2984 "const Foo f = Foo();",
2985 varDecl(hasInitializer(exprWithCleanups()))));
2986}
2987
Daniel Jasper1dad1832012-07-10 20:20:19 +00002988TEST(InitListExpression, MatchesInitListExpression) {
2989 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
2990 initListExpr(hasType(asString("int [2]")))));
2991 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002992 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002993}
2994
2995TEST(UsingDeclaration, MatchesUsingDeclarations) {
2996 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
2997 usingDecl()));
2998}
2999
3000TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3001 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3002 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3003}
3004
3005TEST(UsingDeclaration, MatchesSpecificTarget) {
3006 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3007 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003008 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003009 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3010 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003011 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003012}
3013
3014TEST(UsingDeclaration, ThroughUsingDeclaration) {
3015 EXPECT_TRUE(matches(
3016 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003017 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003018 EXPECT_TRUE(notMatches(
3019 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003020 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003021}
3022
Sam Panzerd624bfb2012-08-16 17:20:59 +00003023TEST(SingleDecl, IsSingleDecl) {
3024 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003025 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003026 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3027 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3028 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3029 SingleDeclStmt));
3030}
3031
3032TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003033 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003034
3035 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003036 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003037 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003038 declStmt(containsDeclaration(0, MatchesInit),
3039 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003040 unsigned WrongIndex = 42;
3041 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003042 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003043 MatchesInit))));
3044}
3045
3046TEST(DeclCount, DeclCountIsCorrect) {
3047 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003048 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003049 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003050 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003051 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003052 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003053}
3054
Manuel Klimek04616e42012-07-06 05:48:52 +00003055TEST(While, MatchesWhileLoops) {
3056 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3057 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3058 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3059}
3060
3061TEST(Do, MatchesDoLoops) {
3062 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3063 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3064}
3065
3066TEST(Do, DoesNotMatchWhileLoops) {
3067 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3068}
3069
3070TEST(SwitchCase, MatchesCase) {
3071 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3072 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3073 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3074 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3075}
3076
Daniel Jasper87c3d362012-09-20 14:12:57 +00003077TEST(SwitchCase, MatchesSwitch) {
3078 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3079 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3080 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3081 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3082}
3083
Peter Collingbourne3154a102013-05-10 11:52:02 +00003084TEST(SwitchCase, MatchesEachCase) {
3085 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3086 switchStmt(forEachSwitchCase(caseStmt()))));
3087 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3088 switchStmt(forEachSwitchCase(caseStmt()))));
3089 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3090 switchStmt(forEachSwitchCase(caseStmt()))));
3091 EXPECT_TRUE(notMatches(
3092 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3093 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3094 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3095 switchStmt(forEachSwitchCase(
3096 caseStmt(hasCaseConstant(integerLiteral()))))));
3097 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3098 switchStmt(forEachSwitchCase(
3099 caseStmt(hasCaseConstant(integerLiteral()))))));
3100 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3101 switchStmt(forEachSwitchCase(
3102 caseStmt(hasCaseConstant(integerLiteral()))))));
3103 EXPECT_TRUE(matchAndVerifyResultTrue(
3104 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3105 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3106 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3107}
3108
Manuel Klimekba46fc02013-07-19 11:50:54 +00003109TEST(ForEachConstructorInitializer, MatchesInitializers) {
3110 EXPECT_TRUE(matches(
3111 "struct X { X() : i(42), j(42) {} int i, j; };",
3112 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3113}
3114
Daniel Jasper87c3d362012-09-20 14:12:57 +00003115TEST(ExceptionHandling, SimpleCases) {
3116 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3117 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3118 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3119 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3120 throwExpr()));
3121 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3122 throwExpr()));
3123}
3124
Manuel Klimek04616e42012-07-06 05:48:52 +00003125TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3126 EXPECT_TRUE(notMatches(
3127 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003128 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003129 EXPECT_TRUE(notMatches(
3130 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003131 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003132}
3133
3134TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3135 EXPECT_TRUE(matches(
3136 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003137 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003138}
3139
3140TEST(ForEach, BindsOneNode) {
3141 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003142 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003143 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003144}
3145
3146TEST(ForEach, BindsMultipleNodes) {
3147 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003148 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003149 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003150}
3151
3152TEST(ForEach, BindsRecursiveCombinations) {
3153 EXPECT_TRUE(matchAndVerifyResultTrue(
3154 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003155 recordDecl(hasName("C"),
3156 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003157 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003158}
3159
3160TEST(ForEachDescendant, BindsOneNode) {
3161 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003162 recordDecl(hasName("C"),
3163 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003164 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003165}
3166
Daniel Jasper94a56852012-11-16 18:39:22 +00003167TEST(ForEachDescendant, NestedForEachDescendant) {
3168 DeclarationMatcher m = recordDecl(
3169 isDefinition(), decl().bind("x"), hasName("C"));
3170 EXPECT_TRUE(matchAndVerifyResultTrue(
3171 "class A { class B { class C {}; }; };",
3172 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3173 new VerifyIdIsBoundTo<Decl>("x", "C")));
3174
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003175 // Check that a partial match of 'm' that binds 'x' in the
3176 // first part of anyOf(m, anything()) will not overwrite the
3177 // binding created by the earlier binding in the hasDescendant.
3178 EXPECT_TRUE(matchAndVerifyResultTrue(
3179 "class A { class B { class C {}; }; };",
3180 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3181 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003182}
3183
Manuel Klimek04616e42012-07-06 05:48:52 +00003184TEST(ForEachDescendant, BindsMultipleNodes) {
3185 EXPECT_TRUE(matchAndVerifyResultTrue(
3186 "class C { class D { int x; int y; }; "
3187 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003188 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003189 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003190}
3191
3192TEST(ForEachDescendant, BindsRecursiveCombinations) {
3193 EXPECT_TRUE(matchAndVerifyResultTrue(
3194 "class C { class D { "
3195 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003196 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3197 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003198 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003199}
3200
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003201TEST(ForEachDescendant, BindsCombinations) {
3202 EXPECT_TRUE(matchAndVerifyResultTrue(
3203 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3204 "(true) {} }",
3205 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3206 forEachDescendant(whileStmt().bind("while"))),
3207 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3208}
3209
3210TEST(Has, DoesNotDeleteBindings) {
3211 EXPECT_TRUE(matchAndVerifyResultTrue(
3212 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3213 new VerifyIdIsBoundTo<Decl>("x", 1)));
3214}
3215
3216TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3217 // Those matchers cover all the cases where an inner matcher is called
3218 // and there is not a 1:1 relationship between the match of the outer
3219 // matcher and the match of the inner matcher.
3220 // The pattern to look for is:
3221 // ... return InnerMatcher.matches(...); ...
3222 // In which case no special handling is needed.
3223 //
3224 // On the other hand, if there are multiple alternative matches
3225 // (for example forEach*) or matches might be discarded (for example has*)
3226 // the implementation must make sure that the discarded matches do not
3227 // affect the bindings.
3228 // When new such matchers are added, add a test here that:
3229 // - matches a simple node, and binds it as the first thing in the matcher:
3230 // recordDecl(decl().bind("x"), hasName("X")))
3231 // - uses the matcher under test afterwards in a way that not the first
3232 // alternative is matched; for anyOf, that means the first branch
3233 // would need to return false; for hasAncestor, it means that not
3234 // the direct parent matches the inner matcher.
3235
3236 EXPECT_TRUE(matchAndVerifyResultTrue(
3237 "class X { int y; };",
3238 recordDecl(
3239 recordDecl().bind("x"), hasName("::X"),
3240 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3241 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3242 EXPECT_TRUE(matchAndVerifyResultTrue(
3243 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3244 anyOf(unless(anything()), anything())),
3245 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3246 EXPECT_TRUE(matchAndVerifyResultTrue(
3247 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3248 classTemplateSpecializationDecl(
3249 decl().bind("x"),
3250 hasAnyTemplateArgument(refersToType(asString("int")))),
3251 new VerifyIdIsBoundTo<Decl>("x", 1)));
3252 EXPECT_TRUE(matchAndVerifyResultTrue(
3253 "class X { void f(); void g(); };",
3254 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3255 new VerifyIdIsBoundTo<Decl>("x", 1)));
3256 EXPECT_TRUE(matchAndVerifyResultTrue(
3257 "class X { X() : a(1), b(2) {} double a; int b; };",
3258 recordDecl(decl().bind("x"),
3259 has(constructorDecl(
3260 hasAnyConstructorInitializer(forField(hasName("b")))))),
3261 new VerifyIdIsBoundTo<Decl>("x", 1)));
3262 EXPECT_TRUE(matchAndVerifyResultTrue(
3263 "void x(int, int) { x(0, 42); }",
3264 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3265 new VerifyIdIsBoundTo<Expr>("x", 1)));
3266 EXPECT_TRUE(matchAndVerifyResultTrue(
3267 "void x(int, int y) {}",
3268 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3269 new VerifyIdIsBoundTo<Decl>("x", 1)));
3270 EXPECT_TRUE(matchAndVerifyResultTrue(
3271 "void x() { return; if (true) {} }",
3272 functionDecl(decl().bind("x"),
3273 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3274 new VerifyIdIsBoundTo<Decl>("x", 1)));
3275 EXPECT_TRUE(matchAndVerifyResultTrue(
3276 "namespace X { void b(int); void b(); }"
3277 "using X::b;",
3278 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3279 functionDecl(parameterCountIs(1))))),
3280 new VerifyIdIsBoundTo<Decl>("x", 1)));
3281 EXPECT_TRUE(matchAndVerifyResultTrue(
3282 "class A{}; class B{}; class C : B, A {};",
3283 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3284 new VerifyIdIsBoundTo<Decl>("x", 1)));
3285 EXPECT_TRUE(matchAndVerifyResultTrue(
3286 "class A{}; typedef A B; typedef A C; typedef A D;"
3287 "class E : A {};",
3288 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3289 new VerifyIdIsBoundTo<Decl>("x", 1)));
3290 EXPECT_TRUE(matchAndVerifyResultTrue(
3291 "class A { class B { void f() {} }; };",
3292 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3293 new VerifyIdIsBoundTo<Decl>("x", 1)));
3294 EXPECT_TRUE(matchAndVerifyResultTrue(
3295 "template <typename T> struct A { struct B {"
3296 " void f() { if(true) {} }"
3297 "}; };"
3298 "void t() { A<int>::B b; b.f(); }",
3299 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3300 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3301 EXPECT_TRUE(matchAndVerifyResultTrue(
3302 "class A {};",
3303 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3304 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003305 EXPECT_TRUE(matchAndVerifyResultTrue(
3306 "class A { A() : s(), i(42) {} const char *s; int i; };",
3307 constructorDecl(hasName("::A::A"), decl().bind("x"),
3308 forEachConstructorInitializer(forField(hasName("i")))),
3309 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003310}
3311
Daniel Jasper33806cd2012-11-11 22:14:55 +00003312TEST(ForEachDescendant, BindsCorrectNodes) {
3313 EXPECT_TRUE(matchAndVerifyResultTrue(
3314 "class C { void f(); int i; };",
3315 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3316 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3317 EXPECT_TRUE(matchAndVerifyResultTrue(
3318 "class C { void f() {} int i; };",
3319 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3320 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3321}
3322
Manuel Klimekabf43712013-02-04 10:59:20 +00003323TEST(FindAll, BindsNodeOnMatch) {
3324 EXPECT_TRUE(matchAndVerifyResultTrue(
3325 "class A {};",
3326 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3327 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3328}
3329
3330TEST(FindAll, BindsDescendantNodeOnMatch) {
3331 EXPECT_TRUE(matchAndVerifyResultTrue(
3332 "class A { int a; int b; };",
3333 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3334 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3335}
3336
3337TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3338 EXPECT_TRUE(matchAndVerifyResultTrue(
3339 "class A { int a; int b; };",
3340 recordDecl(hasName("::A"),
3341 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3342 fieldDecl().bind("v"))))),
3343 new VerifyIdIsBoundTo<Decl>("v", 3)));
3344
3345 EXPECT_TRUE(matchAndVerifyResultTrue(
3346 "class A { class B {}; class C {}; };",
3347 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3348 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3349}
3350
Manuel Klimek88b95872013-02-04 09:42:38 +00003351TEST(EachOf, TriggersForEachMatch) {
3352 EXPECT_TRUE(matchAndVerifyResultTrue(
3353 "class A { int a; int b; };",
3354 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3355 has(fieldDecl(hasName("b")).bind("v")))),
3356 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3357}
3358
3359TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3360 EXPECT_TRUE(matchAndVerifyResultTrue(
3361 "class A { int a; int c; };",
3362 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3363 has(fieldDecl(hasName("b")).bind("v")))),
3364 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3365 EXPECT_TRUE(matchAndVerifyResultTrue(
3366 "class A { int c; int b; };",
3367 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3368 has(fieldDecl(hasName("b")).bind("v")))),
3369 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3370 EXPECT_TRUE(notMatches(
3371 "class A { int c; int d; };",
3372 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3373 has(fieldDecl(hasName("b")).bind("v"))))));
3374}
Manuel Klimek04616e42012-07-06 05:48:52 +00003375
3376TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3377 // Make sure that we can both match the class by name (::X) and by the type
3378 // the template was instantiated with (via a field).
3379
3380 EXPECT_TRUE(matches(
3381 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003382 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003383
3384 EXPECT_TRUE(matches(
3385 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003386 recordDecl(isTemplateInstantiation(), hasDescendant(
3387 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003388}
3389
3390TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3391 EXPECT_TRUE(matches(
3392 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003393 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003394 isTemplateInstantiation())));
3395}
3396
3397TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3398 EXPECT_TRUE(matches(
3399 "template <typename T> class X { T t; }; class A {};"
3400 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003401 recordDecl(isTemplateInstantiation(), hasDescendant(
3402 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003403}
3404
3405TEST(IsTemplateInstantiation,
3406 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3407 EXPECT_TRUE(matches(
3408 "template <typename T> class X {};"
3409 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003410 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003411}
3412
3413TEST(IsTemplateInstantiation,
3414 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3415 EXPECT_TRUE(matches(
3416 "class A {};"
3417 "class X {"
3418 " template <typename U> class Y { U u; };"
3419 " Y<A> y;"
3420 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003421 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003422}
3423
3424TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3425 // FIXME: Figure out whether this makes sense. It doesn't affect the
3426 // normal use case as long as the uppermost instantiation always is marked
3427 // as template instantiation, but it might be confusing as a predicate.
3428 EXPECT_TRUE(matches(
3429 "class A {};"
3430 "template <typename T> class X {"
3431 " template <typename U> class Y { U u; };"
3432 " Y<T> y;"
3433 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003434 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003435}
3436
3437TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3438 EXPECT_TRUE(notMatches(
3439 "template <typename T> class X {}; class A {};"
3440 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003441 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003442}
3443
3444TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3445 EXPECT_TRUE(notMatches(
3446 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003447 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003448}
3449
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003450TEST(IsExplicitTemplateSpecialization,
3451 DoesNotMatchPrimaryTemplate) {
3452 EXPECT_TRUE(notMatches(
3453 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003454 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003455 EXPECT_TRUE(notMatches(
3456 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003457 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003458}
3459
3460TEST(IsExplicitTemplateSpecialization,
3461 DoesNotMatchExplicitTemplateInstantiations) {
3462 EXPECT_TRUE(notMatches(
3463 "template <typename T> class X {};"
3464 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003465 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003466 EXPECT_TRUE(notMatches(
3467 "template <typename T> void f(T t) {}"
3468 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003469 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003470}
3471
3472TEST(IsExplicitTemplateSpecialization,
3473 DoesNotMatchImplicitTemplateInstantiations) {
3474 EXPECT_TRUE(notMatches(
3475 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003476 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003477 EXPECT_TRUE(notMatches(
3478 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003479 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003480}
3481
3482TEST(IsExplicitTemplateSpecialization,
3483 MatchesExplicitTemplateSpecializations) {
3484 EXPECT_TRUE(matches(
3485 "template <typename T> class X {};"
3486 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003487 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003488 EXPECT_TRUE(matches(
3489 "template <typename T> void f(T t) {}"
3490 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003491 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003492}
3493
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003494TEST(HasAncenstor, MatchesDeclarationAncestors) {
3495 EXPECT_TRUE(matches(
3496 "class A { class B { class C {}; }; };",
3497 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3498}
3499
3500TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3501 EXPECT_TRUE(notMatches(
3502 "class A { class B { class C {}; }; };",
3503 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3504}
3505
3506TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3507 EXPECT_TRUE(matches(
3508 "class A { class B { void f() { C c; } class C {}; }; };",
3509 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3510 hasAncestor(recordDecl(hasName("A"))))))));
3511}
3512
3513TEST(HasAncenstor, MatchesStatementAncestors) {
3514 EXPECT_TRUE(matches(
3515 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003516 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003517}
3518
3519TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3520 EXPECT_TRUE(matches(
3521 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003522 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003523}
3524
3525TEST(HasAncestor, BindsRecursiveCombinations) {
3526 EXPECT_TRUE(matchAndVerifyResultTrue(
3527 "class C { class D { class E { class F { int y; }; }; }; };",
3528 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003529 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003530}
3531
3532TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3533 EXPECT_TRUE(matchAndVerifyResultTrue(
3534 "class C { class D { class E { class F { int y; }; }; }; };",
3535 fieldDecl(hasAncestor(
3536 decl(
3537 hasDescendant(recordDecl(isDefinition(),
3538 hasAncestor(recordDecl())))
3539 ).bind("d")
3540 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003541 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003542}
3543
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003544TEST(HasAncestor, MatchesClosestAncestor) {
3545 EXPECT_TRUE(matchAndVerifyResultTrue(
3546 "template <typename T> struct C {"
3547 " void f(int) {"
3548 " struct I { void g(T) { int x; } } i; i.g(42);"
3549 " }"
3550 "};"
3551 "template struct C<int>;",
3552 varDecl(hasName("x"),
3553 hasAncestor(functionDecl(hasParameter(
3554 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3555 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3556}
3557
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003558TEST(HasAncestor, MatchesInTemplateInstantiations) {
3559 EXPECT_TRUE(matches(
3560 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3561 "A<int>::B::C a;",
3562 fieldDecl(hasType(asString("int")),
3563 hasAncestor(recordDecl(hasName("A"))))));
3564}
3565
3566TEST(HasAncestor, MatchesInImplicitCode) {
3567 EXPECT_TRUE(matches(
3568 "struct X {}; struct A { A() {} X x; };",
3569 constructorDecl(
3570 hasAnyConstructorInitializer(withInitializer(expr(
3571 hasAncestor(recordDecl(hasName("A")))))))));
3572}
3573
Daniel Jasper632aea92012-10-22 16:26:51 +00003574TEST(HasParent, MatchesOnlyParent) {
3575 EXPECT_TRUE(matches(
3576 "void f() { if (true) { int x = 42; } }",
3577 compoundStmt(hasParent(ifStmt()))));
3578 EXPECT_TRUE(notMatches(
3579 "void f() { for (;;) { int x = 42; } }",
3580 compoundStmt(hasParent(ifStmt()))));
3581 EXPECT_TRUE(notMatches(
3582 "void f() { if (true) for (;;) { int x = 42; } }",
3583 compoundStmt(hasParent(ifStmt()))));
3584}
3585
Manuel Klimekc844a462012-12-06 14:42:48 +00003586TEST(HasAncestor, MatchesAllAncestors) {
3587 EXPECT_TRUE(matches(
3588 "template <typename T> struct C { static void f() { 42; } };"
3589 "void t() { C<int>::f(); }",
3590 integerLiteral(
3591 equals(42),
3592 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3593 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3594}
3595
3596TEST(HasParent, MatchesAllParents) {
3597 EXPECT_TRUE(matches(
3598 "template <typename T> struct C { static void f() { 42; } };"
3599 "void t() { C<int>::f(); }",
3600 integerLiteral(
3601 equals(42),
3602 hasParent(compoundStmt(hasParent(functionDecl(
3603 hasParent(recordDecl(isTemplateInstantiation())))))))));
3604 EXPECT_TRUE(matches(
3605 "template <typename T> struct C { static void f() { 42; } };"
3606 "void t() { C<int>::f(); }",
3607 integerLiteral(
3608 equals(42),
3609 hasParent(compoundStmt(hasParent(functionDecl(
3610 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3611 EXPECT_TRUE(matches(
3612 "template <typename T> struct C { static void f() { 42; } };"
3613 "void t() { C<int>::f(); }",
3614 integerLiteral(equals(42),
3615 hasParent(compoundStmt(allOf(
3616 hasParent(functionDecl(
3617 hasParent(recordDecl(isTemplateInstantiation())))),
3618 hasParent(functionDecl(hasParent(recordDecl(
3619 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003620 EXPECT_TRUE(
3621 notMatches("template <typename T> struct C { static void f() {} };"
3622 "void t() { C<int>::f(); }",
3623 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003624}
3625
Daniel Jasper516b02e2012-10-17 08:52:59 +00003626TEST(TypeMatching, MatchesTypes) {
3627 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3628}
3629
3630TEST(TypeMatching, MatchesArrayTypes) {
3631 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3632 EXPECT_TRUE(matches("int a[42];", arrayType()));
3633 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3634
3635 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3636 arrayType(hasElementType(builtinType()))));
3637
3638 EXPECT_TRUE(matches(
3639 "int const a[] = { 2, 3 };",
3640 qualType(arrayType(hasElementType(builtinType())))));
3641 EXPECT_TRUE(matches(
3642 "int const a[] = { 2, 3 };",
3643 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3644 EXPECT_TRUE(matches(
3645 "typedef const int T; T x[] = { 1, 2 };",
3646 qualType(isConstQualified(), arrayType())));
3647
3648 EXPECT_TRUE(notMatches(
3649 "int a[] = { 2, 3 };",
3650 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3651 EXPECT_TRUE(notMatches(
3652 "int a[] = { 2, 3 };",
3653 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3654 EXPECT_TRUE(notMatches(
3655 "int const a[] = { 2, 3 };",
3656 qualType(arrayType(hasElementType(builtinType())),
3657 unless(isConstQualified()))));
3658
3659 EXPECT_TRUE(matches("int a[2];",
3660 constantArrayType(hasElementType(builtinType()))));
3661 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3662}
3663
3664TEST(TypeMatching, MatchesComplexTypes) {
3665 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3666 EXPECT_TRUE(matches(
3667 "_Complex float f;",
3668 complexType(hasElementType(builtinType()))));
3669 EXPECT_TRUE(notMatches(
3670 "_Complex float f;",
3671 complexType(hasElementType(isInteger()))));
3672}
3673
3674TEST(TypeMatching, MatchesConstantArrayTypes) {
3675 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3676 EXPECT_TRUE(notMatches(
3677 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3678 constantArrayType(hasElementType(builtinType()))));
3679
3680 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3681 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3682 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3683}
3684
3685TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3686 EXPECT_TRUE(matches(
3687 "template <typename T, int Size> class array { T data[Size]; };",
3688 dependentSizedArrayType()));
3689 EXPECT_TRUE(notMatches(
3690 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3691 dependentSizedArrayType()));
3692}
3693
3694TEST(TypeMatching, MatchesIncompleteArrayType) {
3695 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3696 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3697
3698 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3699 incompleteArrayType()));
3700}
3701
3702TEST(TypeMatching, MatchesVariableArrayType) {
3703 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3704 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3705
3706 EXPECT_TRUE(matches(
3707 "void f(int b) { int a[b]; }",
3708 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3709 varDecl(hasName("b")))))))));
3710}
3711
3712TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003713 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3714 llvm::Triple::Win32) {
3715 // FIXME: Make this work for MSVC.
3716 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003717
David Majnemer197e2102014-03-05 06:32:38 +00003718 EXPECT_TRUE(matches("_Atomic(int) i;",
3719 atomicType(hasValueType(isInteger()))));
3720 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3721 atomicType(hasValueType(isInteger()))));
3722 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003723}
3724
3725TEST(TypeMatching, MatchesAutoTypes) {
3726 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3727 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3728 autoType()));
3729
Richard Smith061f1e22013-04-30 21:23:01 +00003730 // FIXME: Matching against the type-as-written can't work here, because the
3731 // type as written was not deduced.
3732 //EXPECT_TRUE(matches("auto a = 1;",
3733 // autoType(hasDeducedType(isInteger()))));
3734 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3735 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003736}
3737
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00003738TEST(TypeMatching, MatchesFunctionTypes) {
3739 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3740 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3741}
3742
Edwin Vaneec074802013-04-01 18:33:34 +00003743TEST(TypeMatching, MatchesParenType) {
3744 EXPECT_TRUE(
3745 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3746 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3747
3748 EXPECT_TRUE(matches(
3749 "int (*ptr_to_func)(int);",
3750 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3751 EXPECT_TRUE(notMatches(
3752 "int (*ptr_to_array)[4];",
3753 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3754}
3755
Daniel Jasper516b02e2012-10-17 08:52:59 +00003756TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003757 // FIXME: Reactive when these tests can be more specific (not matching
3758 // implicit code on certain platforms), likely when we have hasDescendant for
3759 // Types/TypeLocs.
3760 //EXPECT_TRUE(matchAndVerifyResultTrue(
3761 // "int* a;",
3762 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3763 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3764 //EXPECT_TRUE(matchAndVerifyResultTrue(
3765 // "int* a;",
3766 // pointerTypeLoc().bind("loc"),
3767 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003768 EXPECT_TRUE(matches(
3769 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003770 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003771 EXPECT_TRUE(matches(
3772 "int** a;",
3773 loc(pointerType(pointee(pointerType())))));
3774 EXPECT_TRUE(matches(
3775 "int* b; int* * const a = &b;",
3776 loc(qualType(isConstQualified(), pointerType()))));
3777
3778 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00003779 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3780 hasType(blockPointerType()))));
3781 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3782 hasType(memberPointerType()))));
3783 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3784 hasType(pointerType()))));
3785 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3786 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003787 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3788 hasType(lValueReferenceType()))));
3789 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3790 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003791
Daniel Jasper7943eb52012-10-17 13:35:36 +00003792 Fragment = "int *ptr;";
3793 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3794 hasType(blockPointerType()))));
3795 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3796 hasType(memberPointerType()))));
3797 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
3798 hasType(pointerType()))));
3799 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
3800 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003801
Daniel Jasper7943eb52012-10-17 13:35:36 +00003802 Fragment = "int a; int &ref = a;";
3803 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3804 hasType(blockPointerType()))));
3805 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3806 hasType(memberPointerType()))));
3807 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3808 hasType(pointerType()))));
3809 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3810 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00003811 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3812 hasType(lValueReferenceType()))));
3813 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3814 hasType(rValueReferenceType()))));
3815
3816 Fragment = "int &&ref = 2;";
3817 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3818 hasType(blockPointerType()))));
3819 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3820 hasType(memberPointerType()))));
3821 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3822 hasType(pointerType()))));
3823 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3824 hasType(referenceType()))));
3825 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
3826 hasType(lValueReferenceType()))));
3827 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
3828 hasType(rValueReferenceType()))));
3829}
3830
3831TEST(TypeMatching, AutoRefTypes) {
3832 std::string Fragment = "auto a = 1;"
3833 "auto b = a;"
3834 "auto &c = a;"
3835 "auto &&d = c;"
3836 "auto &&e = 2;";
3837 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
3838 hasType(referenceType()))));
3839 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
3840 hasType(referenceType()))));
3841 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3842 hasType(referenceType()))));
3843 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
3844 hasType(lValueReferenceType()))));
3845 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
3846 hasType(rValueReferenceType()))));
3847 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3848 hasType(referenceType()))));
3849 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
3850 hasType(lValueReferenceType()))));
3851 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
3852 hasType(rValueReferenceType()))));
3853 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3854 hasType(referenceType()))));
3855 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
3856 hasType(lValueReferenceType()))));
3857 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
3858 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003859}
3860
3861TEST(TypeMatching, PointeeTypes) {
3862 EXPECT_TRUE(matches("int b; int &a = b;",
3863 referenceType(pointee(builtinType()))));
3864 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
3865
3866 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003867 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003868
3869 EXPECT_TRUE(matches(
3870 "int const *A;",
3871 pointerType(pointee(isConstQualified(), builtinType()))));
3872 EXPECT_TRUE(notMatches(
3873 "int *A;",
3874 pointerType(pointee(isConstQualified(), builtinType()))));
3875}
3876
3877TEST(TypeMatching, MatchesPointersToConstTypes) {
3878 EXPECT_TRUE(matches("int b; int * const a = &b;",
3879 loc(pointerType())));
3880 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00003881 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003882 EXPECT_TRUE(matches(
3883 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00003884 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003885 EXPECT_TRUE(matches(
3886 "int b; const int * a = &b;",
3887 pointerType(pointee(builtinType()))));
3888}
3889
3890TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003891 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
3892 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003893}
3894
Edwin Vanef901b712013-02-25 14:49:29 +00003895TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00003896 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00003897 templateSpecializationType()));
3898}
3899
Edwin Vaneb6eae142013-02-25 20:43:32 +00003900TEST(TypeMatching, MatchesRecordType) {
3901 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00003902 EXPECT_TRUE(matches("struct S{}; S s;",
3903 recordType(hasDeclaration(recordDecl(hasName("S"))))));
3904 EXPECT_TRUE(notMatches("int i;",
3905 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00003906}
3907
3908TEST(TypeMatching, MatchesElaboratedType) {
3909 EXPECT_TRUE(matches(
3910 "namespace N {"
3911 " namespace M {"
3912 " class D {};"
3913 " }"
3914 "}"
3915 "N::M::D d;", elaboratedType()));
3916 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
3917 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
3918}
3919
3920TEST(ElaboratedTypeNarrowing, hasQualifier) {
3921 EXPECT_TRUE(matches(
3922 "namespace N {"
3923 " namespace M {"
3924 " class D {};"
3925 " }"
3926 "}"
3927 "N::M::D d;",
3928 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
3929 EXPECT_TRUE(notMatches(
3930 "namespace M {"
3931 " class D {};"
3932 "}"
3933 "M::D d;",
3934 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00003935 EXPECT_TRUE(notMatches(
3936 "struct D {"
3937 "} d;",
3938 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00003939}
3940
3941TEST(ElaboratedTypeNarrowing, namesType) {
3942 EXPECT_TRUE(matches(
3943 "namespace N {"
3944 " namespace M {"
3945 " class D {};"
3946 " }"
3947 "}"
3948 "N::M::D d;",
3949 elaboratedType(elaboratedType(namesType(recordType(
3950 hasDeclaration(namedDecl(hasName("D")))))))));
3951 EXPECT_TRUE(notMatches(
3952 "namespace M {"
3953 " class D {};"
3954 "}"
3955 "M::D d;",
3956 elaboratedType(elaboratedType(namesType(typedefType())))));
3957}
3958
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003959TEST(NNS, MatchesNestedNameSpecifiers) {
3960 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
3961 nestedNameSpecifier()));
3962 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
3963 nestedNameSpecifier()));
3964 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
3965 nestedNameSpecifier()));
3966
3967 EXPECT_TRUE(matches(
3968 "struct A { static void f() {} }; void g() { A::f(); }",
3969 nestedNameSpecifier()));
3970 EXPECT_TRUE(notMatches(
3971 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
3972 nestedNameSpecifier()));
3973}
3974
Daniel Jasper87c3d362012-09-20 14:12:57 +00003975TEST(NullStatement, SimpleCases) {
3976 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
3977 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
3978}
3979
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003980TEST(NNS, MatchesTypes) {
3981 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
3982 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
3983 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
3984 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
3985 Matcher));
3986 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
3987}
3988
3989TEST(NNS, MatchesNamespaceDecls) {
3990 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
3991 specifiesNamespace(hasName("ns")));
3992 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
3993 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
3994 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
3995}
3996
3997TEST(NNS, BindsNestedNameSpecifiers) {
3998 EXPECT_TRUE(matchAndVerifyResultTrue(
3999 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4000 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4001 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4002}
4003
4004TEST(NNS, BindsNestedNameSpecifierLocs) {
4005 EXPECT_TRUE(matchAndVerifyResultTrue(
4006 "namespace ns { struct B {}; } ns::B b;",
4007 loc(nestedNameSpecifier()).bind("loc"),
4008 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4009}
4010
4011TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4012 EXPECT_TRUE(matches(
4013 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4014 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4015 EXPECT_TRUE(matches(
4016 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004017 nestedNameSpecifierLoc(hasPrefix(
4018 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004019}
4020
Daniel Jasper6fc34332012-10-30 15:42:00 +00004021TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4022 std::string Fragment =
4023 "namespace a { struct A { struct B { struct C {}; }; }; };"
4024 "void f() { a::A::B::C c; }";
4025 EXPECT_TRUE(matches(
4026 Fragment,
4027 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4028 hasDescendant(nestedNameSpecifier(
4029 specifiesNamespace(hasName("a")))))));
4030 EXPECT_TRUE(notMatches(
4031 Fragment,
4032 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4033 has(nestedNameSpecifier(
4034 specifiesNamespace(hasName("a")))))));
4035 EXPECT_TRUE(matches(
4036 Fragment,
4037 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4038 has(nestedNameSpecifier(
4039 specifiesNamespace(hasName("a")))))));
4040
4041 // Not really useful because a NestedNameSpecifier can af at most one child,
4042 // but to complete the interface.
4043 EXPECT_TRUE(matchAndVerifyResultTrue(
4044 Fragment,
4045 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4046 forEach(nestedNameSpecifier().bind("x"))),
4047 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4048}
4049
4050TEST(NNS, NestedNameSpecifiersAsDescendants) {
4051 std::string Fragment =
4052 "namespace a { struct A { struct B { struct C {}; }; }; };"
4053 "void f() { a::A::B::C c; }";
4054 EXPECT_TRUE(matches(
4055 Fragment,
4056 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4057 asString("struct a::A")))))));
4058 EXPECT_TRUE(matchAndVerifyResultTrue(
4059 Fragment,
4060 functionDecl(hasName("f"),
4061 forEachDescendant(nestedNameSpecifier().bind("x"))),
4062 // Nested names: a, a::A and a::A::B.
4063 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4064}
4065
4066TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4067 std::string Fragment =
4068 "namespace a { struct A { struct B { struct C {}; }; }; };"
4069 "void f() { a::A::B::C c; }";
4070 EXPECT_TRUE(matches(
4071 Fragment,
4072 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4073 hasDescendant(loc(nestedNameSpecifier(
4074 specifiesNamespace(hasName("a"))))))));
4075 EXPECT_TRUE(notMatches(
4076 Fragment,
4077 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4078 has(loc(nestedNameSpecifier(
4079 specifiesNamespace(hasName("a"))))))));
4080 EXPECT_TRUE(matches(
4081 Fragment,
4082 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4083 has(loc(nestedNameSpecifier(
4084 specifiesNamespace(hasName("a"))))))));
4085
4086 EXPECT_TRUE(matchAndVerifyResultTrue(
4087 Fragment,
4088 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4089 forEach(nestedNameSpecifierLoc().bind("x"))),
4090 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4091}
4092
4093TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4094 std::string Fragment =
4095 "namespace a { struct A { struct B { struct C {}; }; }; };"
4096 "void f() { a::A::B::C c; }";
4097 EXPECT_TRUE(matches(
4098 Fragment,
4099 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4100 asString("struct a::A"))))))));
4101 EXPECT_TRUE(matchAndVerifyResultTrue(
4102 Fragment,
4103 functionDecl(hasName("f"),
4104 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4105 // Nested names: a, a::A and a::A::B.
4106 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4107}
4108
Manuel Klimek191c0932013-02-01 13:41:35 +00004109template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004110public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004111 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4112 StringRef InnerId)
4113 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004114 }
4115
Manuel Klimek191c0932013-02-01 13:41:35 +00004116 virtual bool run(const BoundNodes *Nodes) { return false; }
4117
Manuel Klimekc2687452012-10-24 14:47:44 +00004118 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4119 const T *Node = Nodes->getNodeAs<T>(Id);
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004120 return selectFirst<const T>(InnerId,
Craig Topper416fa342014-06-08 08:38:12 +00004121 match(InnerMatcher, *Node, *Context)) !=nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004122 }
4123private:
4124 std::string Id;
4125 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004126 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004127};
4128
4129TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004130 EXPECT_TRUE(matchAndVerifyResultTrue(
4131 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4132 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004133 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4134 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004135 EXPECT_TRUE(matchAndVerifyResultFalse(
4136 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4137 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004138 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4139 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004140}
4141
4142TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004143 EXPECT_TRUE(matchAndVerifyResultTrue(
4144 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004145 new VerifyMatchOnNode<clang::Stmt>(
4146 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004147 EXPECT_TRUE(matchAndVerifyResultFalse(
4148 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004149 new VerifyMatchOnNode<clang::Stmt>(
4150 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004151}
4152
4153TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4154 EXPECT_TRUE(matchAndVerifyResultTrue(
4155 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4156 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004157 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004158 EXPECT_TRUE(matchAndVerifyResultFalse(
4159 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4160 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004161 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004162}
4163
Manuel Klimekbee08572013-02-07 12:42:10 +00004164template <typename T>
4165class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4166public:
4167 virtual bool run(const BoundNodes *Nodes) { return false; }
4168
4169 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4170 const T *Node = Nodes->getNodeAs<T>("");
4171 return verify(*Nodes, *Context, Node);
4172 }
4173
4174 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004175 // Use the original typed pointer to verify we can pass pointers to subtypes
4176 // to equalsNode.
4177 const T *TypedNode = cast<T>(Node);
Manuel Klimekbee08572013-02-07 12:42:10 +00004178 return selectFirst<const T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004179 "", match(stmt(hasParent(
4180 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004181 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004182 }
4183 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004184 // Use the original typed pointer to verify we can pass pointers to subtypes
4185 // to equalsNode.
4186 const T *TypedNode = cast<T>(Node);
Manuel Klimekbee08572013-02-07 12:42:10 +00004187 return selectFirst<const T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004188 "", match(decl(hasParent(
4189 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004190 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004191 }
4192};
4193
4194TEST(IsEqualTo, MatchesNodesByIdentity) {
4195 EXPECT_TRUE(matchAndVerifyResultTrue(
4196 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004197 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4198 EXPECT_TRUE(matchAndVerifyResultTrue(
4199 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4200 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004201}
4202
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004203class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4204public:
4205 VerifyStartOfTranslationUnit() : Called(false) {}
4206 virtual void run(const MatchFinder::MatchResult &Result) {
4207 EXPECT_TRUE(Called);
4208 }
4209 virtual void onStartOfTranslationUnit() {
4210 Called = true;
4211 }
4212 bool Called;
4213};
4214
4215TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4216 MatchFinder Finder;
4217 VerifyStartOfTranslationUnit VerifyCallback;
4218 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004219 std::unique_ptr<FrontendActionFactory> Factory(
4220 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004221 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4222 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004223
4224 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004225 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004226 ASSERT_TRUE(AST.get());
4227 Finder.matchAST(AST->getASTContext());
4228 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004229}
4230
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004231class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4232public:
4233 VerifyEndOfTranslationUnit() : Called(false) {}
4234 virtual void run(const MatchFinder::MatchResult &Result) {
4235 EXPECT_FALSE(Called);
4236 }
4237 virtual void onEndOfTranslationUnit() {
4238 Called = true;
4239 }
4240 bool Called;
4241};
4242
4243TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4244 MatchFinder Finder;
4245 VerifyEndOfTranslationUnit VerifyCallback;
4246 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004247 std::unique_ptr<FrontendActionFactory> Factory(
4248 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004249 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4250 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004251
4252 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004253 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004254 ASSERT_TRUE(AST.get());
4255 Finder.matchAST(AST->getASTContext());
4256 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004257}
4258
Manuel Klimekbbb75852013-06-20 14:06:32 +00004259TEST(EqualsBoundNodeMatcher, QualType) {
4260 EXPECT_TRUE(matches(
4261 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4262 hasInitializer(ignoringParenImpCasts(
4263 hasType(qualType(equalsBoundNode("type"))))))));
4264 EXPECT_TRUE(notMatches("int i = 1.f;",
4265 varDecl(hasType(qualType().bind("type")),
4266 hasInitializer(ignoringParenImpCasts(hasType(
4267 qualType(equalsBoundNode("type"))))))));
4268}
4269
4270TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4271 EXPECT_TRUE(notMatches(
4272 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4273 hasInitializer(ignoringParenImpCasts(
4274 hasType(qualType(equalsBoundNode("type"))))))));
4275}
4276
4277TEST(EqualsBoundNodeMatcher, Stmt) {
4278 EXPECT_TRUE(
4279 matches("void f() { if(true) {} }",
4280 stmt(allOf(ifStmt().bind("if"),
4281 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4282
4283 EXPECT_TRUE(notMatches(
4284 "void f() { if(true) { if (true) {} } }",
4285 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4286}
4287
4288TEST(EqualsBoundNodeMatcher, Decl) {
4289 EXPECT_TRUE(matches(
4290 "class X { class Y {}; };",
4291 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4292 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4293
4294 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4295 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4296 has(decl(equalsBoundNode("record")))))));
4297}
4298
4299TEST(EqualsBoundNodeMatcher, Type) {
4300 EXPECT_TRUE(matches(
4301 "class X { int a; int b; };",
4302 recordDecl(
4303 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4304 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4305
4306 EXPECT_TRUE(notMatches(
4307 "class X { int a; double b; };",
4308 recordDecl(
4309 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4310 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4311}
4312
4313TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004314 EXPECT_TRUE(matchAndVerifyResultTrue(
4315 "int f() {"
4316 " if (1) {"
4317 " int i = 9;"
4318 " }"
4319 " int j = 10;"
4320 " {"
4321 " float k = 9.0;"
4322 " }"
4323 " return 0;"
4324 "}",
4325 // Look for variable declarations within functions whose type is the same
4326 // as the function return type.
4327 functionDecl(returns(qualType().bind("type")),
4328 forEachDescendant(varDecl(hasType(
4329 qualType(equalsBoundNode("type")))).bind("decl"))),
4330 // Only i and j should match, not k.
4331 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4332}
4333
4334TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4335 EXPECT_TRUE(matchAndVerifyResultTrue(
4336 "void f() {"
4337 " int x;"
4338 " double d;"
4339 " x = d + x - d + x;"
4340 "}",
4341 functionDecl(
4342 hasName("f"), forEachDescendant(varDecl().bind("d")),
4343 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4344 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4345}
4346
Manuel Klimekce68f772014-03-25 14:39:26 +00004347TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4348 EXPECT_TRUE(matchAndVerifyResultTrue(
4349 "struct StringRef { int size() const; const char* data() const; };"
4350 "void f(StringRef v) {"
4351 " v.data();"
4352 "}",
4353 memberCallExpr(
4354 callee(methodDecl(hasName("data"))),
4355 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4356 .bind("var")))),
4357 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4358 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4359 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4360 .bind("data"),
4361 new VerifyIdIsBoundTo<Expr>("data", 1)));
4362
4363 EXPECT_FALSE(matches(
4364 "struct StringRef { int size() const; const char* data() const; };"
4365 "void f(StringRef v) {"
4366 " v.data();"
4367 " v.size();"
4368 "}",
4369 memberCallExpr(
4370 callee(methodDecl(hasName("data"))),
4371 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4372 .bind("var")))),
4373 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4374 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4375 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4376 .bind("data")));
4377}
4378
Manuel Klimek04616e42012-07-06 05:48:52 +00004379} // end namespace ast_matchers
4380} // end namespace clang