blob: 5a8f42a87c9626b1d0f1334e759278fab7590eae [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()))))));
Samuel Benzaquend93fcc12014-10-27 20:58:44 +0000378
379 EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000380}
381
Manuel Klimek94ad0bf2014-09-04 08:51:06 +0000382TEST(DeclarationMatcher, LinkageSpecification) {
383 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
384 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
385}
386
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000387TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000388 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000389 EXPECT_TRUE(notMatches("class X;", ClassX));
390 EXPECT_TRUE(notMatches("class X {};", ClassX));
391}
392
393TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000394 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000395 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
396 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
397}
398
399TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
400 EXPECT_TRUE(notMatches("template<typename T> class X { };"
401 "template<> class X<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
406TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
407 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
408 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000409 classTemplateDecl(hasName("X"),
410 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000411}
412
Daniel Jasper4e566c42012-07-12 08:50:38 +0000413TEST(AllOf, AllOverloadsWork) {
414 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000415 "struct T { };"
416 "int f(int, T*, int, int);"
417 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000418 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000419 callExpr(allOf(callee(functionDecl(hasName("f"))),
420 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000421 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000422 callExpr(allOf(callee(functionDecl(hasName("f"))),
423 hasArgument(0, declRefExpr(to(varDecl()))),
424 hasArgument(1, hasType(pointsTo(
425 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000426 EXPECT_TRUE(matches(Program,
427 callExpr(allOf(callee(functionDecl(hasName("f"))),
428 hasArgument(0, declRefExpr(to(varDecl()))),
429 hasArgument(1, hasType(pointsTo(
430 recordDecl(hasName("T"))))),
431 hasArgument(2, integerLiteral(equals(3)))))));
432 EXPECT_TRUE(matches(Program,
433 callExpr(allOf(callee(functionDecl(hasName("f"))),
434 hasArgument(0, declRefExpr(to(varDecl()))),
435 hasArgument(1, hasType(pointsTo(
436 recordDecl(hasName("T"))))),
437 hasArgument(2, integerLiteral(equals(3))),
438 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000439}
440
Manuel Klimek04616e42012-07-06 05:48:52 +0000441TEST(DeclarationMatcher, MatchAnyOf) {
442 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000443 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000444 EXPECT_TRUE(
445 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
446 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
447 EXPECT_TRUE(
448 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
449 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
450
Daniel Jasper84c763e2012-07-15 19:57:12 +0000451 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000452 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000453 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
454 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
455
Manuel Klimek04616e42012-07-06 05:48:52 +0000456 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000457 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
458 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000459 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
460 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
461 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
462 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
463 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
464 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000465
466 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
467 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
468 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
469 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Manuel Klimek04616e42012-07-06 05:48:52 +0000470}
471
472TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000473 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000474 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
475 EXPECT_TRUE(matches("class X {};", HasClassX));
476
477 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000478 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000479 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
480 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
481 EXPECT_TRUE(
482 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
483}
484
485TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
486 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000487 recordDecl(
488 has(recordDecl(
489 has(recordDecl(hasName("X"))),
490 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000491 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000492 has(recordDecl(
493 has(recordDecl(hasName("A"))),
494 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000495 hasName("C"))),
496 hasName("F"));
497
498 EXPECT_TRUE(matches(
499 "class F {"
500 " class Z {"
501 " class X {};"
502 " class Y {};"
503 " };"
504 " class C {"
505 " class A {};"
506 " class B {};"
507 " };"
508 "};", Recursive));
509
510 EXPECT_TRUE(matches(
511 "class F {"
512 " class Z {"
513 " class A {};"
514 " class X {};"
515 " class Y {};"
516 " };"
517 " class C {"
518 " class X {};"
519 " class A {};"
520 " class B {};"
521 " };"
522 "};", Recursive));
523
524 EXPECT_TRUE(matches(
525 "class O1 {"
526 " class O2 {"
527 " class F {"
528 " class Z {"
529 " class A {};"
530 " class X {};"
531 " class Y {};"
532 " };"
533 " class C {"
534 " class X {};"
535 " class A {};"
536 " class B {};"
537 " };"
538 " };"
539 " };"
540 "};", Recursive));
541}
542
543TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
544 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000545 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000546 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000547 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000548 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000549 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000550 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000551 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000552 hasName("Y"))),
553 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000554 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000555 anyOf(
556 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000557 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000558 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000559 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000560 hasName("B")))))),
561 hasName("F")));
562
563 EXPECT_TRUE(matches("class F {};", Recursive));
564 EXPECT_TRUE(matches("class Z {};", Recursive));
565 EXPECT_TRUE(matches("class C {};", Recursive));
566 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
567 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
568 EXPECT_TRUE(
569 matches("class O1 { class O2 {"
570 " class M { class N { class B {}; }; }; "
571 "}; };", Recursive));
572}
573
574TEST(DeclarationMatcher, MatchNot) {
575 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000576 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000577 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000578 unless(hasName("X")));
579 EXPECT_TRUE(notMatches("", NotClassX));
580 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
581 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
582 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
583 EXPECT_TRUE(
584 notMatches("class Y {}; class Z {}; class X : public Y {};",
585 NotClassX));
586
587 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000588 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000589 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000590 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000591 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000592 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000593 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
594 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
595 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000596
597 DeclarationMatcher NamedNotRecord =
598 namedDecl(hasName("Foo"), unless(recordDecl()));
599 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
600 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000601}
602
603TEST(DeclarationMatcher, HasDescendant) {
604 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000605 recordDecl(
606 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000607 hasName("Z"));
608 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
609 EXPECT_TRUE(
610 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
611 EXPECT_TRUE(
612 matches("class Z { class A { class Y { class X {}; }; }; };",
613 ZDescendantClassX));
614 EXPECT_TRUE(
615 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
616 ZDescendantClassX));
617 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
618
619 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000620 recordDecl(
621 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000622 hasName("X"))),
623 hasName("Z"));
624 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
625 ZDescendantClassXHasClassY));
626 EXPECT_TRUE(
627 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
628 ZDescendantClassXHasClassY));
629 EXPECT_TRUE(notMatches(
630 "class Z {"
631 " class A {"
632 " class B {"
633 " class X {"
634 " class C {"
635 " class Y {};"
636 " };"
637 " };"
638 " }; "
639 " };"
640 "};", ZDescendantClassXHasClassY));
641
642 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000643 recordDecl(
644 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
645 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000646 hasName("Z"));
647 EXPECT_TRUE(
648 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
649 ZDescendantClassXDescendantClassY));
650 EXPECT_TRUE(matches(
651 "class Z {"
652 " class A {"
653 " class X {"
654 " class B {"
655 " class Y {};"
656 " };"
657 " class Y {};"
658 " };"
659 " };"
660 "};", ZDescendantClassXDescendantClassY));
661}
662
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000663TEST(DeclarationMatcher, HasDescendantMemoization) {
664 DeclarationMatcher CannotMemoize =
665 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
666 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
667}
668
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000669TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
670 auto Name = hasName("i");
671 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
672 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
673 // Matching VD first should not make a cache hit for RD.
674 EXPECT_TRUE(notMatches("void f() { int i; }",
675 decl(hasDescendant(VD), hasDescendant(RD))));
676 EXPECT_TRUE(notMatches("void f() { int i; }",
677 decl(hasDescendant(RD), hasDescendant(VD))));
678 // Not matching RD first should not make a cache hit for VD either.
679 EXPECT_TRUE(matches("void f() { int i; }",
680 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
681}
682
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000683TEST(DeclarationMatcher, HasAttr) {
684 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
685 decl(hasAttr(clang::attr::WarnUnused))));
686 EXPECT_FALSE(matches("struct X {};",
687 decl(hasAttr(clang::attr::WarnUnused))));
688}
689
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000690TEST(DeclarationMatcher, MatchCudaDecl) {
691 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
692 "void g() { f<<<1, 2>>>(); }",
693 CUDAKernelCallExpr()));
694 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000695 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000696 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000697 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000698 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000699 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000700}
701
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000702// Implements a run method that returns whether BoundNodes contains a
703// Decl bound to Id that can be dynamically cast to T.
704// Optionally checks that the check succeeded a specific number of times.
705template <typename T>
706class VerifyIdIsBoundTo : public BoundNodesCallback {
707public:
708 // Create an object that checks that a node of type \c T was bound to \c Id.
709 // Does not check for a certain number of matches.
710 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
711 : Id(Id), ExpectedCount(-1), Count(0) {}
712
713 // Create an object that checks that a node of type \c T was bound to \c Id.
714 // Checks that there were exactly \c ExpectedCount matches.
715 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
716 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
717
718 // Create an object that checks that a node of type \c T was bound to \c Id.
719 // Checks that there was exactly one match with the name \c ExpectedName.
720 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000721 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
722 int ExpectedCount = 1)
723 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
724 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000725
Craig Toppera798a9d2014-03-02 09:32:10 +0000726 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000727 if (ExpectedCount != -1)
728 EXPECT_EQ(ExpectedCount, Count);
729 if (!ExpectedName.empty())
730 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000731 Count = 0;
732 Name.clear();
733 }
734
735 ~VerifyIdIsBoundTo() {
736 EXPECT_EQ(0, Count);
737 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000738 }
739
Fariborz Jahanian5afc8692014-10-01 16:56:40 +0000740 virtual bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000741 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000742 if (Nodes->getNodeAs<T>(Id)) {
743 ++Count;
744 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
745 Name = Named->getNameAsString();
746 } else if (const NestedNameSpecifier *NNS =
747 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
748 llvm::raw_string_ostream OS(Name);
749 NNS->print(OS, PrintingPolicy(LangOptions()));
750 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000751 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
752 EXPECT_NE(M.end(), I);
753 if (I != M.end())
754 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000755 return true;
756 }
Craig Topper416fa342014-06-08 08:38:12 +0000757 EXPECT_TRUE(M.count(Id) == 0 ||
758 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000759 return false;
760 }
761
Fariborz Jahanian5afc8692014-10-01 16:56:40 +0000762 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000763 return run(Nodes);
764 }
765
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000766private:
767 const std::string Id;
768 const int ExpectedCount;
769 int Count;
770 const std::string ExpectedName;
771 std::string Name;
772};
773
774TEST(HasDescendant, MatchesDescendantTypes) {
775 EXPECT_TRUE(matches("void f() { int i = 3; }",
776 decl(hasDescendant(loc(builtinType())))));
777 EXPECT_TRUE(matches("void f() { int i = 3; }",
778 stmt(hasDescendant(builtinType()))));
779
780 EXPECT_TRUE(matches("void f() { int i = 3; }",
781 stmt(hasDescendant(loc(builtinType())))));
782 EXPECT_TRUE(matches("void f() { int i = 3; }",
783 stmt(hasDescendant(qualType(builtinType())))));
784
785 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
786 stmt(hasDescendant(isInteger()))));
787
788 EXPECT_TRUE(matchAndVerifyResultTrue(
789 "void f() { int a; float c; int d; int e; }",
790 functionDecl(forEachDescendant(
791 varDecl(hasDescendant(isInteger())).bind("x"))),
792 new VerifyIdIsBoundTo<Decl>("x", 3)));
793}
794
795TEST(HasDescendant, MatchesDescendantsOfTypes) {
796 EXPECT_TRUE(matches("void f() { int*** i; }",
797 qualType(hasDescendant(builtinType()))));
798 EXPECT_TRUE(matches("void f() { int*** i; }",
799 qualType(hasDescendant(
800 pointerType(pointee(builtinType()))))));
801 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000802 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000803
804 EXPECT_TRUE(matchAndVerifyResultTrue(
805 "void f() { int*** i; }",
806 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
807 new VerifyIdIsBoundTo<Type>("x", 2)));
808}
809
810TEST(Has, MatchesChildrenOfTypes) {
811 EXPECT_TRUE(matches("int i;",
812 varDecl(hasName("i"), has(isInteger()))));
813 EXPECT_TRUE(notMatches("int** i;",
814 varDecl(hasName("i"), has(isInteger()))));
815 EXPECT_TRUE(matchAndVerifyResultTrue(
816 "int (*f)(float, int);",
817 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
818 new VerifyIdIsBoundTo<QualType>("x", 2)));
819}
820
821TEST(Has, MatchesChildTypes) {
822 EXPECT_TRUE(matches(
823 "int* i;",
824 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
825 EXPECT_TRUE(notMatches(
826 "int* i;",
827 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
828}
829
Daniel Jasper1dad1832012-07-10 20:20:19 +0000830TEST(Enum, DoesNotMatchClasses) {
831 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
832}
833
834TEST(Enum, MatchesEnums) {
835 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
836}
837
838TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000839 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000840 EXPECT_TRUE(matches("enum X{ A };", Matcher));
841 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
842 EXPECT_TRUE(notMatches("enum X {};", Matcher));
843}
844
Manuel Klimek04616e42012-07-06 05:48:52 +0000845TEST(StatementMatcher, Has) {
846 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000847 expr(hasType(pointsTo(recordDecl(hasName("X")))),
848 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000849
850 EXPECT_TRUE(matches(
851 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
852 EXPECT_TRUE(notMatches(
853 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
854}
855
856TEST(StatementMatcher, HasDescendant) {
857 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000858 expr(hasType(pointsTo(recordDecl(hasName("X")))),
859 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000860
861 EXPECT_TRUE(matches(
862 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
863 HasDescendantVariableI));
864 EXPECT_TRUE(notMatches(
865 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
866 HasDescendantVariableI));
867}
868
869TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000870 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000871
872 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
873 EXPECT_TRUE(notMatches("class A {};", TypeA));
874
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000875 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000876
877 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
878 TypeDerivedFromA));
879 EXPECT_TRUE(notMatches("class A {};", TypeA));
880
881 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000882 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000883
884 EXPECT_TRUE(
885 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
886}
887
Manuel Klimek04616e42012-07-06 05:48:52 +0000888TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000889 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000890
891 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000892 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000893
894 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000895 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000896
897 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000898 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000899
900 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
901 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000902 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000903
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000904 StatementMatcher MethodX =
905 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000906
907 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
908 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000909 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000910}
911
912TEST(Matcher, BindTheSameNameInAlternatives) {
913 StatementMatcher matcher = anyOf(
914 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000915 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000916 hasRHS(integerLiteral(equals(0)))),
917 binaryOperator(hasOperatorName("+"),
918 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000919 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000920
921 EXPECT_TRUE(matchAndVerifyResultTrue(
922 // The first branch of the matcher binds x to 0 but then fails.
923 // The second branch binds x to f() and succeeds.
924 "int f() { return 0 + f(); }",
925 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000926 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000927}
928
Manuel Klimekfdf98762012-08-30 19:41:06 +0000929TEST(Matcher, BindsIDForMemoizedResults) {
930 // Using the same matcher in two match expressions will make memoization
931 // kick in.
932 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
933 EXPECT_TRUE(matchAndVerifyResultTrue(
934 "class A { class B { class X {}; }; };",
935 DeclarationMatcher(anyOf(
936 recordDecl(hasName("A"), hasDescendant(ClassX)),
937 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000938 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000939}
940
Daniel Jasper856194d02012-12-03 15:43:25 +0000941TEST(HasDeclaration, HasDeclarationOfEnumType) {
942 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
943 expr(hasType(pointsTo(
944 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
945}
946
Edwin Vaneed936452013-02-25 14:32:42 +0000947TEST(HasDeclaration, HasGetDeclTraitTest) {
948 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
949 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
950 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
951}
952
Edwin Vane2c197e02013-02-19 17:14:34 +0000953TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
954 EXPECT_TRUE(matches("typedef int X; X a;",
955 varDecl(hasName("a"),
956 hasType(typedefType(hasDeclaration(decl()))))));
957
958 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
959}
960
Edwin Vanef901b712013-02-25 14:49:29 +0000961TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
962 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
963 varDecl(hasType(templateSpecializationType(
964 hasDeclaration(namedDecl(hasName("A"))))))));
965}
966
Manuel Klimek04616e42012-07-06 05:48:52 +0000967TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000968 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000969 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000970 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000971 EXPECT_TRUE(
972 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000973 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000974 EXPECT_TRUE(
975 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000976 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000977}
978
979TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000980 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000981 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000982 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000983 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000984 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000985 EXPECT_TRUE(
986 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000987 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000988}
989
990TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000991 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000992 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000993 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000994 EXPECT_TRUE(
995 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000996 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000997}
998
999TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001000 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001001 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001002 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001003 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001004 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001005}
1006
Manuel Klimekc16c6522013-06-20 13:08:29 +00001007TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1008 EXPECT_TRUE(matches("int x;",
1009 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1010
1011 // Make sure we don't crash on implicit constructors.
1012 EXPECT_TRUE(notMatches("class X {}; X x;",
1013 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1014}
1015
Manuel Klimek04616e42012-07-06 05:48:52 +00001016TEST(Matcher, Call) {
1017 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001018 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001019 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001020
1021 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1022 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1023
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001024 StatementMatcher MethodOnY =
1025 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001026
1027 EXPECT_TRUE(
1028 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1029 MethodOnY));
1030 EXPECT_TRUE(
1031 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1032 MethodOnY));
1033 EXPECT_TRUE(
1034 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1035 MethodOnY));
1036 EXPECT_TRUE(
1037 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1038 MethodOnY));
1039 EXPECT_TRUE(
1040 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1041 MethodOnY));
1042
1043 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001044 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001045
1046 EXPECT_TRUE(
1047 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1048 MethodOnYPointer));
1049 EXPECT_TRUE(
1050 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1051 MethodOnYPointer));
1052 EXPECT_TRUE(
1053 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1054 MethodOnYPointer));
1055 EXPECT_TRUE(
1056 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1057 MethodOnYPointer));
1058 EXPECT_TRUE(
1059 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1060 MethodOnYPointer));
1061}
1062
Daniel Jasper5901e472012-10-01 13:40:41 +00001063TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001064 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001065 lambdaExpr()));
1066}
1067
1068TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001069 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1070 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001071 forRangeStmt()));
1072 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1073 forRangeStmt()));
1074}
1075
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001076TEST(Matcher, SubstNonTypeTemplateParm) {
1077 EXPECT_FALSE(matches("template<int N>\n"
1078 "struct A { static const int n = 0; };\n"
1079 "struct B : public A<42> {};",
1080 substNonTypeTemplateParmExpr()));
1081 EXPECT_TRUE(matches("template<int N>\n"
1082 "struct A { static const int n = N; };\n"
1083 "struct B : public A<42> {};",
1084 substNonTypeTemplateParmExpr()));
1085}
1086
Daniel Jasper5901e472012-10-01 13:40:41 +00001087TEST(Matcher, UserDefinedLiteral) {
1088 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1089 " return i + 1;"
1090 "}"
1091 "char c = 'a'_inc;",
1092 userDefinedLiteral()));
1093}
1094
Daniel Jasper87c3d362012-09-20 14:12:57 +00001095TEST(Matcher, FlowControl) {
1096 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1097 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1098 continueStmt()));
1099 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1100 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1101 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1102}
1103
Daniel Jasper1dad1832012-07-10 20:20:19 +00001104TEST(HasType, MatchesAsString) {
1105 EXPECT_TRUE(
1106 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001107 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001108 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001109 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001110 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001111 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001112 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001113 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001114}
1115
Manuel Klimek04616e42012-07-06 05:48:52 +00001116TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001117 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001118 // Unary operator
1119 EXPECT_TRUE(matches("class Y { }; "
1120 "bool operator!(Y x) { return false; }; "
1121 "Y y; bool c = !y;", OpCall));
1122 // No match -- special operators like "new", "delete"
1123 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1124 // we need to figure out include paths in the test.
1125 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1126 // "class Y { }; "
1127 // "void *operator new(size_t size) { return 0; } "
1128 // "Y *y = new Y;", OpCall));
1129 EXPECT_TRUE(notMatches("class Y { }; "
1130 "void operator delete(void *p) { } "
1131 "void a() {Y *y = new Y; delete y;}", OpCall));
1132 // Binary operator
1133 EXPECT_TRUE(matches("class Y { }; "
1134 "bool operator&&(Y x, Y y) { return true; }; "
1135 "Y a; Y b; bool c = a && b;",
1136 OpCall));
1137 // No match -- normal operator, not an overloaded one.
1138 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1139 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1140}
1141
1142TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1143 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001144 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001145 EXPECT_TRUE(matches("class Y { }; "
1146 "bool operator&&(Y x, Y y) { return true; }; "
1147 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1148 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001149 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001150 EXPECT_TRUE(notMatches("class Y { }; "
1151 "bool operator&&(Y x, Y y) { return true; }; "
1152 "Y a; Y b; bool c = a && b;",
1153 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001154 StatementMatcher OpStarCall =
1155 operatorCallExpr(hasOverloadedOperatorName("*"));
1156 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1157 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001158 DeclarationMatcher ClassWithOpStar =
1159 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1160 EXPECT_TRUE(matches("class Y { int operator*(); };",
1161 ClassWithOpStar));
1162 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1163 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001164 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1165 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1166 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001167}
1168
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001169TEST(Matcher, NestedOverloadedOperatorCalls) {
1170 EXPECT_TRUE(matchAndVerifyResultTrue(
1171 "class Y { }; "
1172 "Y& operator&&(Y& x, Y& y) { return x; }; "
1173 "Y a; Y b; Y c; Y d = a && b && c;",
1174 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1175 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1176 EXPECT_TRUE(matches(
1177 "class Y { }; "
1178 "Y& operator&&(Y& x, Y& y) { return x; }; "
1179 "Y a; Y b; Y c; Y d = a && b && c;",
1180 operatorCallExpr(hasParent(operatorCallExpr()))));
1181 EXPECT_TRUE(matches(
1182 "class Y { }; "
1183 "Y& operator&&(Y& x, Y& y) { return x; }; "
1184 "Y a; Y b; Y c; Y d = a && b && c;",
1185 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1186}
1187
Manuel Klimek04616e42012-07-06 05:48:52 +00001188TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001189 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001190 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001191
1192 EXPECT_TRUE(
1193 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1194 MethodOnY));
1195 EXPECT_TRUE(
1196 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1197 MethodOnY));
1198 EXPECT_TRUE(
1199 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1200 MethodOnY));
1201 EXPECT_TRUE(
1202 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1203 MethodOnY));
1204 EXPECT_TRUE(
1205 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1206 MethodOnY));
1207
1208 EXPECT_TRUE(matches(
1209 "class Y {"
1210 " public: virtual void x();"
1211 "};"
1212 "class X : public Y {"
1213 " public: virtual void x();"
1214 "};"
1215 "void z() { X *x; x->Y::x(); }", MethodOnY));
1216}
1217
1218TEST(Matcher, VariableUsage) {
1219 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001220 declRefExpr(to(
1221 varDecl(hasInitializer(
1222 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001223
1224 EXPECT_TRUE(matches(
1225 "class Y {"
1226 " public:"
1227 " bool x() const;"
1228 "};"
1229 "void z(const Y &y) {"
1230 " bool b = y.x();"
1231 " if (b) {}"
1232 "}", Reference));
1233
1234 EXPECT_TRUE(notMatches(
1235 "class Y {"
1236 " public:"
1237 " bool x() const;"
1238 "};"
1239 "void z(const Y &y) {"
1240 " bool b = y.x();"
1241 "}", Reference));
1242}
1243
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001244TEST(Matcher, VarDecl_Storage) {
1245 auto M = varDecl(hasName("X"), hasLocalStorage());
1246 EXPECT_TRUE(matches("void f() { int X; }", M));
1247 EXPECT_TRUE(notMatches("int X;", M));
1248 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1249
1250 M = varDecl(hasName("X"), hasGlobalStorage());
1251 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1252 EXPECT_TRUE(matches("int X;", M));
1253 EXPECT_TRUE(matches("void f() { static int X; }", M));
1254}
1255
Manuel Klimek61379422012-12-04 14:42:08 +00001256TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001257 EXPECT_TRUE(matches(
1258 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001259 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001260}
1261
Manuel Klimek04616e42012-07-06 05:48:52 +00001262TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001263 StatementMatcher CallOnVariableY =
1264 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001265
1266 EXPECT_TRUE(matches(
1267 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1268 EXPECT_TRUE(matches(
1269 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1270 EXPECT_TRUE(matches(
1271 "class Y { public: void x(); };"
1272 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1273 EXPECT_TRUE(matches(
1274 "class Y { public: void x(); };"
1275 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1276 EXPECT_TRUE(notMatches(
1277 "class Y { public: void x(); };"
1278 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1279 CallOnVariableY));
1280}
1281
Daniel Jasper1dad1832012-07-10 20:20:19 +00001282TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1283 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1284 unaryExprOrTypeTraitExpr()));
1285 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1286 alignOfExpr(anything())));
1287 // FIXME: Uncomment once alignof is enabled.
1288 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1289 // unaryExprOrTypeTraitExpr()));
1290 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1291 // sizeOfExpr()));
1292}
1293
1294TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1295 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1296 hasArgumentOfType(asString("int")))));
1297 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1298 hasArgumentOfType(asString("float")))));
1299 EXPECT_TRUE(matches(
1300 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001301 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001302 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001303 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001304}
1305
Manuel Klimek04616e42012-07-06 05:48:52 +00001306TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001307 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001308}
1309
1310TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001311 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001312}
1313
1314TEST(MemberExpression, MatchesVariable) {
1315 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001316 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001317 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001318 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001319 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001320 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001321}
1322
1323TEST(MemberExpression, MatchesStaticVariable) {
1324 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001325 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001326 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001327 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001328 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001329 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001330}
1331
Daniel Jasper4e566c42012-07-12 08:50:38 +00001332TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001333 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1334 EXPECT_TRUE(matches(
1335 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1336 callExpr(hasArgument(0, declRefExpr(
1337 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001338}
1339
1340TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001341 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001342 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001343 callExpr(hasArgument(0, declRefExpr(
1344 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001345}
1346
Manuel Klimek04616e42012-07-06 05:48:52 +00001347TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1348 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001349 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001350 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001351 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001352 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001353 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001354}
1355
1356TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1357 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001358 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001359 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001360 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001361 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001362 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001363}
1364
1365TEST(IsArrow, MatchesMemberCallsViaArrow) {
1366 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001367 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001368 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001369 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001370 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001371 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001372}
1373
1374TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001375 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001376
1377 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1378 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1379}
1380
1381TEST(Callee, MatchesMemberExpressions) {
1382 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001383 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001384 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001385 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001386}
1387
1388TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001389 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001390
1391 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1392 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1393
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001394 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1395 llvm::Triple::Win32) {
1396 // FIXME: Make this work for MSVC.
1397 // Dependent contexts, but a non-dependent call.
1398 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1399 CallFunctionF));
1400 EXPECT_TRUE(
1401 matches("void f(); template <int N> struct S { void g() { f(); } };",
1402 CallFunctionF));
1403 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001404
1405 // Depedent calls don't match.
1406 EXPECT_TRUE(
1407 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1408 CallFunctionF));
1409 EXPECT_TRUE(
1410 notMatches("void f(int);"
1411 "template <typename T> struct S { void g(T t) { f(t); } };",
1412 CallFunctionF));
1413}
1414
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001415TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1416 EXPECT_TRUE(
1417 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001418 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001419}
1420
1421TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1422 EXPECT_TRUE(
1423 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001424 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001425}
1426
1427TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1428 EXPECT_TRUE(
1429 notMatches("void g(); template <typename T> void f(T t) {}"
1430 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001431 functionTemplateDecl(hasName("f"),
1432 hasDescendant(declRefExpr(to(
1433 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001434}
1435
Manuel Klimek04616e42012-07-06 05:48:52 +00001436TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001437 StatementMatcher CallArgumentY = callExpr(
1438 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001439
1440 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1441 EXPECT_TRUE(
1442 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1443 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1444
Daniel Jasper848cbe12012-09-18 13:09:13 +00001445 StatementMatcher WrongIndex = callExpr(
1446 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001447 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1448}
1449
1450TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001451 StatementMatcher CallArgumentY = callExpr(
1452 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001453 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1454 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1455 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1456}
1457
1458TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001459 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001460
1461 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1462 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1463 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1464}
1465
Daniel Jasper9f501292012-12-04 11:54:27 +00001466TEST(Matcher, ParameterCount) {
1467 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1468 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1469 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1470 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1471 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1472}
1473
Manuel Klimek04616e42012-07-06 05:48:52 +00001474TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001475 DeclarationMatcher ReferenceClassX = varDecl(
1476 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001477 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1478 ReferenceClassX));
1479 EXPECT_TRUE(
1480 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001481 // The match here is on the implicit copy constructor code for
1482 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001483 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001484 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1485 EXPECT_TRUE(
1486 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001487 EXPECT_TRUE(
1488 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1489}
1490
Edwin Vane0a4836e2013-03-06 17:02:57 +00001491TEST(QualType, hasCanonicalType) {
1492 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1493 "int a;"
1494 "int_ref b = a;",
1495 varDecl(hasType(qualType(referenceType())))));
1496 EXPECT_TRUE(
1497 matches("typedef int &int_ref;"
1498 "int a;"
1499 "int_ref b = a;",
1500 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1501}
1502
Edwin Vane119d3df2013-04-02 18:15:55 +00001503TEST(QualType, hasLocalQualifiers) {
1504 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1505 varDecl(hasType(hasLocalQualifiers()))));
1506 EXPECT_TRUE(matches("int *const j = nullptr;",
1507 varDecl(hasType(hasLocalQualifiers()))));
1508 EXPECT_TRUE(matches("int *volatile k;",
1509 varDecl(hasType(hasLocalQualifiers()))));
1510 EXPECT_TRUE(notMatches("int m;",
1511 varDecl(hasType(hasLocalQualifiers()))));
1512}
1513
Manuel Klimek04616e42012-07-06 05:48:52 +00001514TEST(HasParameter, CallsInnerMatcher) {
1515 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001516 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001517 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001518 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001519}
1520
1521TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1522 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001523 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001524}
1525
1526TEST(HasType, MatchesParameterVariableTypesStrictly) {
1527 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001528 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001529 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001530 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001531 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001532 methodDecl(hasParameter(0,
1533 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001534 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001535 methodDecl(hasParameter(0,
1536 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001537}
1538
1539TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1540 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001541 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001542 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001543 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001544}
1545
Daniel Jasper1dad1832012-07-10 20:20:19 +00001546TEST(Returns, MatchesReturnTypes) {
1547 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001548 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001549 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001550 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001551 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001552 functionDecl(returns(hasDeclaration(
1553 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001554}
1555
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001556TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001557 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1558 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1559 functionDecl(isExternC())));
1560 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001561}
1562
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001563TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1564 EXPECT_TRUE(
1565 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1566 EXPECT_TRUE(matches("void Func() = delete;",
1567 functionDecl(hasName("Func"), isDeleted())));
1568}
1569
Manuel Klimek04616e42012-07-06 05:48:52 +00001570TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1571 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001572 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001573}
1574
1575TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1576 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001577 methodDecl(hasAnyParameter(hasType(pointsTo(
1578 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001579}
1580
Alp Toker8db6e7a2014-01-05 06:38:57 +00001581TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001582 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001583 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001584 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001585 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001586}
1587
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001588TEST(Matcher, MatchesClassTemplateSpecialization) {
1589 EXPECT_TRUE(matches("template<typename T> struct A {};"
1590 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001591 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001592 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001593 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001594 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001595 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001596}
1597
Manuel Klimekc16c6522013-06-20 13:08:29 +00001598TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1599 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1600 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1601}
1602
1603TEST(ParmVarDecl, MatchesParmVars) {
1604 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1605 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1606}
1607
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001608TEST(Matcher, MatchesTypeTemplateArgument) {
1609 EXPECT_TRUE(matches(
1610 "template<typename T> struct B {};"
1611 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001612 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001613 asString("int"))))));
1614}
1615
1616TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1617 EXPECT_TRUE(matches(
1618 "struct B { int next; };"
1619 "template<int(B::*next_ptr)> struct A {};"
1620 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001621 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1622 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001623
1624 EXPECT_TRUE(notMatches(
1625 "template <typename T> struct A {};"
1626 "A<int> a;",
1627 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1628 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001629
1630 EXPECT_TRUE(matches(
1631 "struct B { int next; };"
1632 "template<int(B::*next_ptr)> struct A {};"
1633 "A<&B::next> a;",
1634 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1635 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1636
1637 EXPECT_TRUE(notMatches(
1638 "template <typename T> struct A {};"
1639 "A<int> a;",
1640 templateSpecializationType(hasAnyTemplateArgument(
1641 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001642}
1643
1644TEST(Matcher, MatchesSpecificArgument) {
1645 EXPECT_TRUE(matches(
1646 "template<typename T, typename U> class A {};"
1647 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001648 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001649 1, refersToType(asString("int"))))));
1650 EXPECT_TRUE(notMatches(
1651 "template<typename T, typename U> class A {};"
1652 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001653 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001654 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001655
1656 EXPECT_TRUE(matches(
1657 "template<typename T, typename U> class A {};"
1658 "A<bool, int> a;",
1659 templateSpecializationType(hasTemplateArgument(
1660 1, refersToType(asString("int"))))));
1661 EXPECT_TRUE(notMatches(
1662 "template<typename T, typename U> class A {};"
1663 "A<int, bool> a;",
1664 templateSpecializationType(hasTemplateArgument(
1665 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001666}
1667
Manuel Klimek7735e402014-10-09 13:06:22 +00001668TEST(TemplateArgument, Matches) {
1669 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1670 classTemplateSpecializationDecl(
1671 hasAnyTemplateArgument(templateArgument()))));
1672 EXPECT_TRUE(matches(
1673 "template<typename T> struct C {}; C<int> c;",
1674 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1675}
1676
1677TEST(TemplateArgumentCountIs, Matches) {
1678 EXPECT_TRUE(
1679 matches("template<typename T> struct C {}; C<int> c;",
1680 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1681 EXPECT_TRUE(
1682 notMatches("template<typename T> struct C {}; C<int> c;",
1683 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1684
1685 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1686 templateSpecializationType(templateArgumentCountIs(1))));
1687 EXPECT_TRUE(
1688 notMatches("template<typename T> struct C {}; C<int> c;",
1689 templateSpecializationType(templateArgumentCountIs(2))));
1690}
1691
1692TEST(IsIntegral, Matches) {
1693 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1694 classTemplateSpecializationDecl(
1695 hasAnyTemplateArgument(isIntegral()))));
1696 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1697 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1698 templateArgument(isIntegral())))));
1699}
1700
1701TEST(RefersToIntegralType, Matches) {
1702 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1703 classTemplateSpecializationDecl(
1704 hasAnyTemplateArgument(refersToIntegralType(
1705 asString("int"))))));
1706 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1707 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1708 refersToIntegralType(asString("int"))))));
1709}
1710
1711TEST(EqualsIntegralValue, Matches) {
1712 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1713 classTemplateSpecializationDecl(
1714 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1715 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1716 classTemplateSpecializationDecl(
1717 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1718 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1719 classTemplateSpecializationDecl(
1720 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1721 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1722 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1723 equalsIntegralValue("0042")))));
1724}
1725
Daniel Jasper639522c2013-02-25 12:02:08 +00001726TEST(Matcher, MatchesAccessSpecDecls) {
1727 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1728 EXPECT_TRUE(
1729 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1730 EXPECT_TRUE(
1731 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1732 EXPECT_TRUE(
1733 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1734
1735 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1736}
1737
Edwin Vane37ee1d72013-04-09 20:46:36 +00001738TEST(Matcher, MatchesVirtualMethod) {
1739 EXPECT_TRUE(matches("class X { virtual int f(); };",
1740 methodDecl(isVirtual(), hasName("::X::f"))));
1741 EXPECT_TRUE(notMatches("class X { int f(); };",
1742 methodDecl(isVirtual())));
1743}
1744
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001745TEST(Matcher, MatchesPureMethod) {
1746 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1747 methodDecl(isPure(), hasName("::X::f"))));
1748 EXPECT_TRUE(notMatches("class X { int f(); };",
1749 methodDecl(isPure())));
1750}
1751
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001752TEST(Matcher, MatchesConstMethod) {
1753 EXPECT_TRUE(matches("struct A { void foo() const; };",
1754 methodDecl(isConst())));
1755 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1756 methodDecl(isConst())));
1757}
1758
Edwin Vane37ee1d72013-04-09 20:46:36 +00001759TEST(Matcher, MatchesOverridingMethod) {
1760 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1761 "class Y : public X { int f(); };",
1762 methodDecl(isOverride(), hasName("::Y::f"))));
1763 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1764 "class Y : public X { int f(); };",
1765 methodDecl(isOverride(), hasName("::X::f"))));
1766 EXPECT_TRUE(notMatches("class X { int f(); }; "
1767 "class Y : public X { int f(); };",
1768 methodDecl(isOverride())));
1769 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1770 methodDecl(isOverride())));
1771}
1772
Manuel Klimek04616e42012-07-06 05:48:52 +00001773TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001774 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001775
1776 EXPECT_TRUE(
1777 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1778 EXPECT_TRUE(
1779 matches("class X { public: X(); }; void x() { X x = X(); }",
1780 Constructor));
1781 EXPECT_TRUE(
1782 matches("class X { public: X(int); }; void x() { X x = 0; }",
1783 Constructor));
1784 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1785}
1786
1787TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001788 StatementMatcher Constructor = constructExpr(
1789 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001790
1791 EXPECT_TRUE(
1792 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1793 Constructor));
1794 EXPECT_TRUE(
1795 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1796 Constructor));
1797 EXPECT_TRUE(
1798 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1799 Constructor));
1800 EXPECT_TRUE(
1801 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1802 Constructor));
1803
Daniel Jasper848cbe12012-09-18 13:09:13 +00001804 StatementMatcher WrongIndex = constructExpr(
1805 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001806 EXPECT_TRUE(
1807 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1808 WrongIndex));
1809}
1810
1811TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001812 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001813
1814 EXPECT_TRUE(
1815 matches("class X { public: X(int); }; void x() { X x(0); }",
1816 Constructor1Arg));
1817 EXPECT_TRUE(
1818 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1819 Constructor1Arg));
1820 EXPECT_TRUE(
1821 matches("class X { public: X(int); }; void x() { X x = 0; }",
1822 Constructor1Arg));
1823 EXPECT_TRUE(
1824 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1825 Constructor1Arg));
1826}
1827
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001828TEST(Matcher, ConstructorListInitialization) {
1829 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1830
1831 EXPECT_TRUE(
1832 matches("class X { public: X(int); }; void x() { X x{0}; }",
1833 ConstructorListInit));
1834 EXPECT_FALSE(
1835 matches("class X { public: X(int); }; void x() { X x(0); }",
1836 ConstructorListInit));
1837}
1838
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001839TEST(Matcher,ThisExpr) {
1840 EXPECT_TRUE(
1841 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1842 EXPECT_TRUE(
1843 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1844}
1845
Manuel Klimek04616e42012-07-06 05:48:52 +00001846TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001847 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001848
1849 std::string ClassString = "class string { public: string(); ~string(); }; ";
1850
1851 EXPECT_TRUE(
1852 matches(ClassString +
1853 "string GetStringByValue();"
1854 "void FunctionTakesString(string s);"
1855 "void run() { FunctionTakesString(GetStringByValue()); }",
1856 TempExpression));
1857
1858 EXPECT_TRUE(
1859 notMatches(ClassString +
1860 "string* GetStringPointer(); "
1861 "void FunctionTakesStringPtr(string* s);"
1862 "void run() {"
1863 " string* s = GetStringPointer();"
1864 " FunctionTakesStringPtr(GetStringPointer());"
1865 " FunctionTakesStringPtr(s);"
1866 "}",
1867 TempExpression));
1868
1869 EXPECT_TRUE(
1870 notMatches("class no_dtor {};"
1871 "no_dtor GetObjByValue();"
1872 "void ConsumeObj(no_dtor param);"
1873 "void run() { ConsumeObj(GetObjByValue()); }",
1874 TempExpression));
1875}
1876
Sam Panzer68a35af2012-08-24 22:04:44 +00001877TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1878 std::string ClassString =
1879 "class string { public: string(); int length(); }; ";
1880
1881 EXPECT_TRUE(
1882 matches(ClassString +
1883 "string GetStringByValue();"
1884 "void FunctionTakesString(string s);"
1885 "void run() { FunctionTakesString(GetStringByValue()); }",
1886 materializeTemporaryExpr()));
1887
1888 EXPECT_TRUE(
1889 notMatches(ClassString +
1890 "string* GetStringPointer(); "
1891 "void FunctionTakesStringPtr(string* s);"
1892 "void run() {"
1893 " string* s = GetStringPointer();"
1894 " FunctionTakesStringPtr(GetStringPointer());"
1895 " FunctionTakesStringPtr(s);"
1896 "}",
1897 materializeTemporaryExpr()));
1898
1899 EXPECT_TRUE(
1900 notMatches(ClassString +
1901 "string GetStringByValue();"
1902 "void run() { int k = GetStringByValue().length(); }",
1903 materializeTemporaryExpr()));
1904
1905 EXPECT_TRUE(
1906 notMatches(ClassString +
1907 "string GetStringByValue();"
1908 "void run() { GetStringByValue(); }",
1909 materializeTemporaryExpr()));
1910}
1911
Manuel Klimek04616e42012-07-06 05:48:52 +00001912TEST(ConstructorDeclaration, SimpleCase) {
1913 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001914 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001915 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001916 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001917}
1918
1919TEST(ConstructorDeclaration, IsImplicit) {
1920 // This one doesn't match because the constructor is not added by the
1921 // compiler (it is not needed).
1922 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001923 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001924 // The compiler added the implicit default constructor.
1925 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001926 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001927 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001928 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001929 // The compiler added an implicit assignment operator.
1930 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1931 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001932}
1933
Daniel Jasper1dad1832012-07-10 20:20:19 +00001934TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1935 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001936 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001937}
1938
1939TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001940 EXPECT_TRUE(notMatches("class Foo {};",
1941 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001942}
1943
Manuel Klimek04616e42012-07-06 05:48:52 +00001944TEST(HasAnyConstructorInitializer, SimpleCase) {
1945 EXPECT_TRUE(notMatches(
1946 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001947 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001948 EXPECT_TRUE(matches(
1949 "class Foo {"
1950 " Foo() : foo_() { }"
1951 " int foo_;"
1952 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001953 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001954}
1955
1956TEST(HasAnyConstructorInitializer, ForField) {
1957 static const char Code[] =
1958 "class Baz { };"
1959 "class Foo {"
1960 " Foo() : foo_() { }"
1961 " Baz foo_;"
1962 " Baz bar_;"
1963 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001964 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1965 forField(hasType(recordDecl(hasName("Baz"))))))));
1966 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001967 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001968 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1969 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001970}
1971
1972TEST(HasAnyConstructorInitializer, WithInitializer) {
1973 static const char Code[] =
1974 "class Foo {"
1975 " Foo() : foo_(0) { }"
1976 " int foo_;"
1977 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001978 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001979 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001980 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001981 withInitializer(integerLiteral(equals(1)))))));
1982}
1983
1984TEST(HasAnyConstructorInitializer, IsWritten) {
1985 static const char Code[] =
1986 "struct Bar { Bar(){} };"
1987 "class Foo {"
1988 " Foo() : foo_() { }"
1989 " Bar foo_;"
1990 " Bar bar_;"
1991 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001992 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001993 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001994 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001995 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001996 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001997 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1998}
1999
2000TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002001 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002002
2003 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2004 EXPECT_TRUE(
2005 matches("class X { public: X(); }; void x() { new X(); }", New));
2006 EXPECT_TRUE(
2007 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2008 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2009}
2010
2011TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002012 StatementMatcher New = constructExpr(
2013 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002014
2015 EXPECT_TRUE(
2016 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2017 New));
2018 EXPECT_TRUE(
2019 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2020 New));
2021 EXPECT_TRUE(
2022 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2023 New));
2024
Daniel Jasper848cbe12012-09-18 13:09:13 +00002025 StatementMatcher WrongIndex = constructExpr(
2026 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002027 EXPECT_TRUE(
2028 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2029 WrongIndex));
2030}
2031
2032TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002033 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002034
2035 EXPECT_TRUE(
2036 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2037 EXPECT_TRUE(
2038 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2039 New));
2040}
2041
Daniel Jasper1dad1832012-07-10 20:20:19 +00002042TEST(Matcher, DeleteExpression) {
2043 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002044 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002045}
2046
Manuel Klimek04616e42012-07-06 05:48:52 +00002047TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002048 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002049
2050 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2051 EXPECT_TRUE(
2052 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2053 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2054}
2055
2056TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002057 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002058 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2059 // wide string
2060 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2061 // with escaped characters
2062 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2063 // no matching -- though the data type is the same, there is no string literal
2064 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2065}
2066
2067TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002068 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002069 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2070 // wide character
2071 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2072 // wide character, Hex encoded, NOT MATCHED!
2073 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2074 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2075}
2076
2077TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002078 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002079 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2080 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2081 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2082 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2083
2084 // Non-matching cases (character literals, float and double)
2085 EXPECT_TRUE(notMatches("int i = L'a';",
2086 HasIntLiteral)); // this is actually a character
2087 // literal cast to int
2088 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2089 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2090 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2091}
2092
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002093TEST(Matcher, FloatLiterals) {
2094 StatementMatcher HasFloatLiteral = floatLiteral();
2095 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2096 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2097 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2098 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2099 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
2100
2101 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
2102}
2103
Daniel Jasper5901e472012-10-01 13:40:41 +00002104TEST(Matcher, NullPtrLiteral) {
2105 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2106}
2107
Daniel Jasper87c3d362012-09-20 14:12:57 +00002108TEST(Matcher, AsmStatement) {
2109 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2110}
2111
Manuel Klimek04616e42012-07-06 05:48:52 +00002112TEST(Matcher, Conditions) {
2113 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2114
2115 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2116 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2117 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2118 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2119 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2120}
2121
Manuel Klimek909b5c942014-05-27 10:04:12 +00002122TEST(IfStmt, ChildTraversalMatchers) {
2123 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2124 ifStmt(hasThen(boolLiteral(equals(true))))));
2125 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2126 ifStmt(hasThen(boolLiteral(equals(true))))));
2127 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2128 ifStmt(hasElse(boolLiteral(equals(true))))));
2129 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2130 ifStmt(hasElse(boolLiteral(equals(true))))));
2131}
2132
Manuel Klimek04616e42012-07-06 05:48:52 +00002133TEST(MatchBinaryOperator, HasOperatorName) {
2134 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2135
2136 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2137 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2138}
2139
2140TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2141 StatementMatcher OperatorTrueFalse =
2142 binaryOperator(hasLHS(boolLiteral(equals(true))),
2143 hasRHS(boolLiteral(equals(false))));
2144
2145 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2146 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2147 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2148}
2149
2150TEST(MatchBinaryOperator, HasEitherOperand) {
2151 StatementMatcher HasOperand =
2152 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2153
2154 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2155 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2156 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2157}
2158
2159TEST(Matcher, BinaryOperatorTypes) {
2160 // Integration test that verifies the AST provides all binary operators in
2161 // a way we expect.
2162 // FIXME: Operator ','
2163 EXPECT_TRUE(
2164 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2165 EXPECT_TRUE(
2166 matches("bool b; bool c = (b = true);",
2167 binaryOperator(hasOperatorName("="))));
2168 EXPECT_TRUE(
2169 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2170 EXPECT_TRUE(
2171 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2172 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2173 EXPECT_TRUE(
2174 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2175 EXPECT_TRUE(
2176 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2177 EXPECT_TRUE(
2178 matches("int i = 1; int j = (i <<= 2);",
2179 binaryOperator(hasOperatorName("<<="))));
2180 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2181 EXPECT_TRUE(
2182 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2183 EXPECT_TRUE(
2184 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2185 EXPECT_TRUE(
2186 matches("int i = 1; int j = (i >>= 2);",
2187 binaryOperator(hasOperatorName(">>="))));
2188 EXPECT_TRUE(
2189 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2190 EXPECT_TRUE(
2191 matches("int i = 42; int j = (i ^= 42);",
2192 binaryOperator(hasOperatorName("^="))));
2193 EXPECT_TRUE(
2194 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2195 EXPECT_TRUE(
2196 matches("int i = 42; int j = (i %= 42);",
2197 binaryOperator(hasOperatorName("%="))));
2198 EXPECT_TRUE(
2199 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2200 EXPECT_TRUE(
2201 matches("bool b = true && false;",
2202 binaryOperator(hasOperatorName("&&"))));
2203 EXPECT_TRUE(
2204 matches("bool b = true; bool c = (b &= false);",
2205 binaryOperator(hasOperatorName("&="))));
2206 EXPECT_TRUE(
2207 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2208 EXPECT_TRUE(
2209 matches("bool b = true || false;",
2210 binaryOperator(hasOperatorName("||"))));
2211 EXPECT_TRUE(
2212 matches("bool b = true; bool c = (b |= false);",
2213 binaryOperator(hasOperatorName("|="))));
2214 EXPECT_TRUE(
2215 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2216 EXPECT_TRUE(
2217 matches("int i = 42; int j = (i *= 23);",
2218 binaryOperator(hasOperatorName("*="))));
2219 EXPECT_TRUE(
2220 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2221 EXPECT_TRUE(
2222 matches("int i = 42; int j = (i /= 23);",
2223 binaryOperator(hasOperatorName("/="))));
2224 EXPECT_TRUE(
2225 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2226 EXPECT_TRUE(
2227 matches("int i = 42; int j = (i += 23);",
2228 binaryOperator(hasOperatorName("+="))));
2229 EXPECT_TRUE(
2230 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2231 EXPECT_TRUE(
2232 matches("int i = 42; int j = (i -= 23);",
2233 binaryOperator(hasOperatorName("-="))));
2234 EXPECT_TRUE(
2235 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2236 binaryOperator(hasOperatorName("->*"))));
2237 EXPECT_TRUE(
2238 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2239 binaryOperator(hasOperatorName(".*"))));
2240
2241 // Member expressions as operators are not supported in matches.
2242 EXPECT_TRUE(
2243 notMatches("struct A { void x(A *a) { a->x(this); } };",
2244 binaryOperator(hasOperatorName("->"))));
2245
2246 // Initializer assignments are not represented as operator equals.
2247 EXPECT_TRUE(
2248 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2249
2250 // Array indexing is not represented as operator.
2251 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2252
2253 // Overloaded operators do not match at all.
2254 EXPECT_TRUE(notMatches(
2255 "struct A { bool operator&&(const A &a) const { return false; } };"
2256 "void x() { A a, b; a && b; }",
2257 binaryOperator()));
2258}
2259
2260TEST(MatchUnaryOperator, HasOperatorName) {
2261 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2262
2263 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2264 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2265}
2266
2267TEST(MatchUnaryOperator, HasUnaryOperand) {
2268 StatementMatcher OperatorOnFalse =
2269 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2270
2271 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2272 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2273}
2274
2275TEST(Matcher, UnaryOperatorTypes) {
2276 // Integration test that verifies the AST provides all unary operators in
2277 // a way we expect.
2278 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2279 EXPECT_TRUE(
2280 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2281 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2282 EXPECT_TRUE(
2283 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2284 EXPECT_TRUE(
2285 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2286 EXPECT_TRUE(
2287 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2288 EXPECT_TRUE(
2289 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2290 EXPECT_TRUE(
2291 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2292 EXPECT_TRUE(
2293 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2294 EXPECT_TRUE(
2295 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2296
2297 // We don't match conversion operators.
2298 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2299
2300 // Function calls are not represented as operator.
2301 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2302
2303 // Overloaded operators do not match at all.
2304 // FIXME: We probably want to add that.
2305 EXPECT_TRUE(notMatches(
2306 "struct A { bool operator!() const { return false; } };"
2307 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2308}
2309
2310TEST(Matcher, ConditionalOperator) {
2311 StatementMatcher Conditional = conditionalOperator(
2312 hasCondition(boolLiteral(equals(true))),
2313 hasTrueExpression(boolLiteral(equals(false))));
2314
2315 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2316 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2317 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2318
2319 StatementMatcher ConditionalFalse = conditionalOperator(
2320 hasFalseExpression(boolLiteral(equals(false))));
2321
2322 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2323 EXPECT_TRUE(
2324 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2325}
2326
Daniel Jasper1dad1832012-07-10 20:20:19 +00002327TEST(ArraySubscriptMatchers, ArraySubscripts) {
2328 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2329 arraySubscriptExpr()));
2330 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2331 arraySubscriptExpr()));
2332}
2333
2334TEST(ArraySubscriptMatchers, ArrayIndex) {
2335 EXPECT_TRUE(matches(
2336 "int i[2]; void f() { i[1] = 1; }",
2337 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2338 EXPECT_TRUE(matches(
2339 "int i[2]; void f() { 1[i] = 1; }",
2340 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2341 EXPECT_TRUE(notMatches(
2342 "int i[2]; void f() { i[1] = 1; }",
2343 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2344}
2345
2346TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2347 EXPECT_TRUE(matches(
2348 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002349 arraySubscriptExpr(hasBase(implicitCastExpr(
2350 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002351}
2352
Manuel Klimek04616e42012-07-06 05:48:52 +00002353TEST(Matcher, HasNameSupportsNamespaces) {
2354 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002355 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002356 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002357 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002358 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002359 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002360 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002361 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002362 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002363 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002364 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002365 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002366 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002367 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002368 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002369 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002370 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002371 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002372 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002373 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002374 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002375 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002376 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002377 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002378}
2379
2380TEST(Matcher, HasNameSupportsOuterClasses) {
2381 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002382 matches("class A { class B { class C; }; };",
2383 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002384 EXPECT_TRUE(
2385 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002386 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002387 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002388 matches("class A { class B { class C; }; };",
2389 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002390 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002391 matches("class A { class B { class C; }; };",
2392 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002393 EXPECT_TRUE(
2394 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002395 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002396 EXPECT_TRUE(
2397 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002398 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002399 EXPECT_TRUE(
2400 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002401 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002402 EXPECT_TRUE(
2403 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002404 recordDecl(hasName("::C"))));
2405 EXPECT_TRUE(
2406 notMatches("class A { class B { class C; }; };",
2407 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002408 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002409 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002410 EXPECT_TRUE(
2411 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002412 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002413}
2414
2415TEST(Matcher, IsDefinition) {
2416 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002417 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002418 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2419 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2420
2421 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002422 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002423 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2424 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2425
2426 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002427 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002428 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2429 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2430}
2431
2432TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002433 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002434 ofClass(hasName("X")))));
2435
2436 EXPECT_TRUE(
2437 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2438 EXPECT_TRUE(
2439 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2440 Constructor));
2441 EXPECT_TRUE(
2442 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2443 Constructor));
2444}
2445
2446TEST(Matcher, VisitsTemplateInstantiations) {
2447 EXPECT_TRUE(matches(
2448 "class A { public: void x(); };"
2449 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002450 "void f() { B<A> b; b.y(); }",
2451 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002452
2453 EXPECT_TRUE(matches(
2454 "class A { public: void x(); };"
2455 "class C {"
2456 " public:"
2457 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2458 "};"
2459 "void f() {"
2460 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002461 "}",
2462 recordDecl(hasName("C"),
2463 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002464}
2465
Daniel Jasper1dad1832012-07-10 20:20:19 +00002466TEST(Matcher, HandlesNullQualTypes) {
2467 // FIXME: Add a Type matcher so we can replace uses of this
2468 // variable with Type(True())
2469 const TypeMatcher AnyType = anything();
2470
2471 // We don't really care whether this matcher succeeds; we're testing that
2472 // it completes without crashing.
2473 EXPECT_TRUE(matches(
2474 "struct A { };"
2475 "template <typename T>"
2476 "void f(T t) {"
2477 " T local_t(t /* this becomes a null QualType in the AST */);"
2478 "}"
2479 "void g() {"
2480 " f(0);"
2481 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002482 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002483 anyOf(
2484 TypeMatcher(hasDeclaration(anything())),
2485 pointsTo(AnyType),
2486 references(AnyType)
2487 // Other QualType matchers should go here.
2488 ))))));
2489}
2490
Manuel Klimek04616e42012-07-06 05:48:52 +00002491// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002492AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002493 // Make sure all special variables are used: node, match_finder,
2494 // bound_nodes_builder, and the parameter named 'AMatcher'.
2495 return AMatcher.matches(Node, Finder, Builder);
2496}
2497
2498TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002499 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002500
2501 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002502 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002503
2504 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002505 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002506
2507 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002508 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002509}
2510
2511AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +00002512 polymorphicHas,
2513 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2514 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002515 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002516 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002517 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2518 ASTMatchFinder::BK_First);
2519}
2520
2521TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002522 DeclarationMatcher HasClassB =
2523 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002524
2525 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002526 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002527
2528 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002529 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002530
2531 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002532 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002533
2534 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002535 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002536
2537 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2538}
2539
2540TEST(For, FindsForLoops) {
2541 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2542 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002543 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2544 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002545 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002546}
2547
Daniel Jasper4e566c42012-07-12 08:50:38 +00002548TEST(For, ForLoopInternals) {
2549 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2550 forStmt(hasCondition(anything()))));
2551 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2552 forStmt(hasLoopInit(anything()))));
2553}
2554
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002555TEST(For, ForRangeLoopInternals) {
2556 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2557 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002558 EXPECT_TRUE(matches(
2559 "void f(){ int a[] {1, 2}; for (int i : a); }",
2560 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002561}
2562
Daniel Jasper4e566c42012-07-12 08:50:38 +00002563TEST(For, NegativeForLoopInternals) {
2564 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002565 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002566 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2567 forStmt(hasLoopInit(anything()))));
2568}
2569
Manuel Klimek04616e42012-07-06 05:48:52 +00002570TEST(For, ReportsNoFalsePositives) {
2571 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2572 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2573}
2574
2575TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002576 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2577 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2578 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002579}
2580
2581TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2582 // It's not a compound statement just because there's "{}" in the source
2583 // text. This is an AST search, not grep.
2584 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002585 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002586 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002587 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002588}
2589
Daniel Jasper4e566c42012-07-12 08:50:38 +00002590TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002591 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002592 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002593 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002594 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002595 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002596 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002597 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002598 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002599 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2600 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002601}
2602
2603TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2604 // The simplest case: every compound statement is in a function
2605 // definition, and the function body itself must be a compound
2606 // statement.
2607 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002608 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002609}
2610
2611TEST(HasAnySubstatement, IsNotRecursive) {
2612 // It's really "has any immediate substatement".
2613 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002614 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002615}
2616
2617TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2618 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002619 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002620}
2621
2622TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2623 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002624 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002625}
2626
2627TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2628 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002629 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002630 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002631 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002632}
2633
2634TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2635 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002636 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002637 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002638 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002639 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002640 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002641}
2642
2643TEST(StatementCountIs, WorksWithMultipleStatements) {
2644 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002645 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002646}
2647
2648TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2649 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002650 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002651 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002652 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002653 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002654 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002655 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002656 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002657}
2658
2659TEST(Member, WorksInSimplestCase) {
2660 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002661 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002662}
2663
2664TEST(Member, DoesNotMatchTheBaseExpression) {
2665 // Don't pick out the wrong part of the member expression, this should
2666 // be checking the member (name) only.
2667 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002668 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002669}
2670
2671TEST(Member, MatchesInMemberFunctionCall) {
2672 EXPECT_TRUE(matches("void f() {"
2673 " struct { void first() {}; } s;"
2674 " s.first();"
2675 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002676 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002677}
2678
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002679TEST(Member, MatchesMember) {
2680 EXPECT_TRUE(matches(
2681 "struct A { int i; }; void f() { A a; a.i = 2; }",
2682 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2683 EXPECT_TRUE(notMatches(
2684 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2685 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2686}
2687
Daniel Jasper639522c2013-02-25 12:02:08 +00002688TEST(Member, UnderstandsAccess) {
2689 EXPECT_TRUE(matches(
2690 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2691 EXPECT_TRUE(notMatches(
2692 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2693 EXPECT_TRUE(notMatches(
2694 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2695
2696 EXPECT_TRUE(notMatches(
2697 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2698 EXPECT_TRUE(notMatches(
2699 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2700 EXPECT_TRUE(matches(
2701 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2702
2703 EXPECT_TRUE(notMatches(
2704 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2705 EXPECT_TRUE(matches("class A { protected: int i; };",
2706 fieldDecl(isProtected(), hasName("i"))));
2707 EXPECT_TRUE(notMatches(
2708 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2709
2710 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2711 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2712 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2713 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2714}
2715
Dmitri Gribenko06963042012-08-18 00:29:27 +00002716TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002717 // Fails in C++11 mode
2718 EXPECT_TRUE(matchesConditionally(
2719 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2720 "class X { void *operator new(std::size_t); };",
2721 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002722
2723 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002724 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002725
Daniel Jasper5901e472012-10-01 13:40:41 +00002726 // Fails in C++11 mode
2727 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002728 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2729 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002730 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002731}
2732
Manuel Klimek04616e42012-07-06 05:48:52 +00002733TEST(HasObjectExpression, DoesNotMatchMember) {
2734 EXPECT_TRUE(notMatches(
2735 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002736 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002737}
2738
2739TEST(HasObjectExpression, MatchesBaseOfVariable) {
2740 EXPECT_TRUE(matches(
2741 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002742 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002743 EXPECT_TRUE(matches(
2744 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002745 memberExpr(hasObjectExpression(
2746 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002747}
2748
2749TEST(HasObjectExpression,
2750 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2751 EXPECT_TRUE(matches(
2752 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002753 memberExpr(hasObjectExpression(
2754 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002755 EXPECT_TRUE(matches(
2756 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002757 memberExpr(hasObjectExpression(
2758 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002759}
2760
2761TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002762 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2763 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2764 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2765 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002766}
2767
2768TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002769 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002770}
2771
2772TEST(IsConstQualified, MatchesConstInt) {
2773 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002774 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002775}
2776
2777TEST(IsConstQualified, MatchesConstPointer) {
2778 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002779 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002780}
2781
2782TEST(IsConstQualified, MatchesThroughTypedef) {
2783 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002784 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002785 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002786 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002787}
2788
2789TEST(IsConstQualified, DoesNotMatchInappropriately) {
2790 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002791 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002792 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002793 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002794}
2795
Sam Panzer80c13772012-08-16 16:58:10 +00002796TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002797 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2798 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2799 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2800 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002801}
2802TEST(CastExpression, MatchesImplicitCasts) {
2803 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002804 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002805 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002806 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002807}
2808
2809TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002810 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2811 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2812 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2813 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002814}
2815
Manuel Klimek04616e42012-07-06 05:48:52 +00002816TEST(ReinterpretCast, MatchesSimpleCase) {
2817 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002818 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002819}
2820
2821TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002822 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002823 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002824 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002825 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002826 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002827 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2828 "B b;"
2829 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002830 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002831}
2832
2833TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002834 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002835 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002836 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002837}
2838
2839TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002840 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002841 EXPECT_TRUE(
2842 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002843 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002844 EXPECT_TRUE(
2845 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002846 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002847}
2848
2849TEST(DynamicCast, MatchesSimpleCase) {
2850 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2851 "B b;"
2852 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002853 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002854}
2855
2856TEST(StaticCast, MatchesSimpleCase) {
2857 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002858 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002859}
2860
2861TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002862 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002863 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002864 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002865 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002866 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002867 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2868 "B b;"
2869 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002870 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002871}
2872
Daniel Jasper417f7762012-09-18 13:36:17 +00002873TEST(CStyleCast, MatchesSimpleCase) {
2874 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2875}
2876
2877TEST(CStyleCast, DoesNotMatchOtherCasts) {
2878 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2879 "char q, *r = const_cast<char*>(&q);"
2880 "void* s = reinterpret_cast<char*>(&s);"
2881 "struct B { virtual ~B() {} }; struct D : B {};"
2882 "B b;"
2883 "D* t = dynamic_cast<D*>(&b);",
2884 cStyleCastExpr()));
2885}
2886
Manuel Klimek04616e42012-07-06 05:48:52 +00002887TEST(HasDestinationType, MatchesSimpleCase) {
2888 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002889 staticCastExpr(hasDestinationType(
2890 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002891}
2892
Sam Panzer80c13772012-08-16 16:58:10 +00002893TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2894 // This test creates an implicit const cast.
2895 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002896 implicitCastExpr(
2897 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002898 // This test creates an implicit array-to-pointer cast.
2899 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002900 implicitCastExpr(hasImplicitDestinationType(
2901 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002902}
2903
2904TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2905 // This test creates an implicit cast from int to char.
2906 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002907 implicitCastExpr(hasImplicitDestinationType(
2908 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002909 // This test creates an implicit array-to-pointer cast.
2910 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002911 implicitCastExpr(hasImplicitDestinationType(
2912 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002913}
2914
2915TEST(ImplicitCast, MatchesSimpleCase) {
2916 // This test creates an implicit const cast.
2917 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002918 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002919 // This test creates an implicit cast from int to char.
2920 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002921 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002922 // This test creates an implicit array-to-pointer cast.
2923 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002924 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002925}
2926
2927TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002928 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002929 // are present, and that it ignores explicit and paren casts.
2930
2931 // These two test cases have no casts.
2932 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002933 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002934 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002935 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002936
2937 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002938 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002939 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002940 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002941
2942 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002943 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002944}
2945
2946TEST(IgnoringImpCasts, MatchesImpCasts) {
2947 // This test checks that ignoringImpCasts matches when implicit casts are
2948 // present and its inner matcher alone does not match.
2949 // Note that this test creates an implicit const cast.
2950 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002951 varDecl(hasInitializer(ignoringImpCasts(
2952 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002953 // This test creates an implict cast from int to char.
2954 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002955 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002956 integerLiteral(equals(0)))))));
2957}
2958
2959TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2960 // These tests verify that ignoringImpCasts does not match if the inner
2961 // matcher does not match.
2962 // Note that the first test creates an implicit const cast.
2963 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002964 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002965 unless(anything()))))));
2966 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002967 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002968 unless(anything()))))));
2969
2970 // These tests verify that ignoringImplictCasts does not look through explicit
2971 // casts or parentheses.
2972 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002973 varDecl(hasInitializer(ignoringImpCasts(
2974 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002975 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002976 varDecl(hasInitializer(ignoringImpCasts(
2977 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002978 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002979 varDecl(hasInitializer(ignoringImpCasts(
2980 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002981 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002982 varDecl(hasInitializer(ignoringImpCasts(
2983 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002984}
2985
2986TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
2987 // This test verifies that expressions that do not have implicit casts
2988 // still match the inner matcher.
2989 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002990 varDecl(hasInitializer(ignoringImpCasts(
2991 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002992}
2993
2994TEST(IgnoringParenCasts, MatchesParenCasts) {
2995 // This test checks that ignoringParenCasts matches when parentheses and/or
2996 // casts are present and its inner matcher alone does not match.
2997 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002998 varDecl(hasInitializer(ignoringParenCasts(
2999 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003000 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003001 varDecl(hasInitializer(ignoringParenCasts(
3002 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003003
3004 // This test creates an implict cast from int to char in addition to the
3005 // parentheses.
3006 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003007 varDecl(hasInitializer(ignoringParenCasts(
3008 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003009
3010 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003011 varDecl(hasInitializer(ignoringParenCasts(
3012 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003013 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003014 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003015 integerLiteral(equals(0)))))));
3016}
3017
3018TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3019 // This test verifies that expressions that do not have any casts still match.
3020 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003021 varDecl(hasInitializer(ignoringParenCasts(
3022 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003023}
3024
3025TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3026 // These tests verify that ignoringImpCasts does not match if the inner
3027 // matcher does not match.
3028 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003029 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003030 unless(anything()))))));
3031
3032 // This test creates an implicit cast from int to char in addition to the
3033 // parentheses.
3034 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003035 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003036 unless(anything()))))));
3037
3038 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003039 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003040 unless(anything()))))));
3041}
3042
3043TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3044 // This test checks that ignoringParenAndImpCasts matches when
3045 // parentheses and/or implicit casts are present and its inner matcher alone
3046 // does not match.
3047 // Note that this test creates an implicit const cast.
3048 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003049 varDecl(hasInitializer(ignoringParenImpCasts(
3050 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003051 // This test creates an implicit cast from int to char.
3052 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003053 varDecl(hasInitializer(ignoringParenImpCasts(
3054 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003055}
3056
3057TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3058 // This test verifies that expressions that do not have parentheses or
3059 // implicit casts still match.
3060 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003061 varDecl(hasInitializer(ignoringParenImpCasts(
3062 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003063 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003064 varDecl(hasInitializer(ignoringParenImpCasts(
3065 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003066}
3067
3068TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3069 // These tests verify that ignoringParenImpCasts does not match if
3070 // the inner matcher does not match.
3071 // This test creates an implicit cast.
3072 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003073 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003074 unless(anything()))))));
3075 // These tests verify that ignoringParenAndImplictCasts does not look
3076 // through explicit casts.
3077 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003078 varDecl(hasInitializer(ignoringParenImpCasts(
3079 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003080 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003081 varDecl(hasInitializer(ignoringParenImpCasts(
3082 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003083 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003084 varDecl(hasInitializer(ignoringParenImpCasts(
3085 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003086}
3087
Manuel Klimeke9235692012-07-25 10:02:02 +00003088TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003089 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3090 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003091 implicitCastExpr(
3092 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003093}
3094
Manuel Klimeke9235692012-07-25 10:02:02 +00003095TEST(HasSourceExpression, MatchesExplicitCasts) {
3096 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003097 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003098 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003099 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003100}
3101
Manuel Klimek04616e42012-07-06 05:48:52 +00003102TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003103 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003104}
3105
3106TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003107 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003108}
3109
3110TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003111 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003112}
3113
3114TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003115 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003116}
3117
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003118TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3119 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3120 "const Foo f = Foo();",
3121 varDecl(hasInitializer(exprWithCleanups()))));
3122 EXPECT_FALSE(matches("struct Foo { };"
3123 "const Foo f = Foo();",
3124 varDecl(hasInitializer(exprWithCleanups()))));
3125}
3126
Daniel Jasper1dad1832012-07-10 20:20:19 +00003127TEST(InitListExpression, MatchesInitListExpression) {
3128 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3129 initListExpr(hasType(asString("int [2]")))));
3130 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003131 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003132}
3133
3134TEST(UsingDeclaration, MatchesUsingDeclarations) {
3135 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3136 usingDecl()));
3137}
3138
3139TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3140 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3141 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3142}
3143
3144TEST(UsingDeclaration, MatchesSpecificTarget) {
3145 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3146 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003147 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003148 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3149 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003150 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003151}
3152
3153TEST(UsingDeclaration, ThroughUsingDeclaration) {
3154 EXPECT_TRUE(matches(
3155 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003156 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003157 EXPECT_TRUE(notMatches(
3158 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003159 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003160}
3161
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003162TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3163 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3164 usingDirectiveDecl()));
3165 EXPECT_FALSE(
3166 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3167}
3168
Sam Panzerd624bfb2012-08-16 17:20:59 +00003169TEST(SingleDecl, IsSingleDecl) {
3170 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003171 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003172 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3173 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3174 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3175 SingleDeclStmt));
3176}
3177
3178TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003179 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003180
3181 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003182 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003183 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003184 declStmt(containsDeclaration(0, MatchesInit),
3185 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003186 unsigned WrongIndex = 42;
3187 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003188 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003189 MatchesInit))));
3190}
3191
3192TEST(DeclCount, DeclCountIsCorrect) {
3193 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003194 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003195 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003196 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003197 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003198 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003199}
3200
Manuel Klimek04616e42012-07-06 05:48:52 +00003201TEST(While, MatchesWhileLoops) {
3202 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3203 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3204 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3205}
3206
3207TEST(Do, MatchesDoLoops) {
3208 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3209 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3210}
3211
3212TEST(Do, DoesNotMatchWhileLoops) {
3213 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3214}
3215
3216TEST(SwitchCase, MatchesCase) {
3217 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3218 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3219 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3220 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3221}
3222
Daniel Jasper87c3d362012-09-20 14:12:57 +00003223TEST(SwitchCase, MatchesSwitch) {
3224 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3225 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3226 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3227 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3228}
3229
Peter Collingbourne3154a102013-05-10 11:52:02 +00003230TEST(SwitchCase, MatchesEachCase) {
3231 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3232 switchStmt(forEachSwitchCase(caseStmt()))));
3233 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3234 switchStmt(forEachSwitchCase(caseStmt()))));
3235 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3236 switchStmt(forEachSwitchCase(caseStmt()))));
3237 EXPECT_TRUE(notMatches(
3238 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3239 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3240 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3241 switchStmt(forEachSwitchCase(
3242 caseStmt(hasCaseConstant(integerLiteral()))))));
3243 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3244 switchStmt(forEachSwitchCase(
3245 caseStmt(hasCaseConstant(integerLiteral()))))));
3246 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3247 switchStmt(forEachSwitchCase(
3248 caseStmt(hasCaseConstant(integerLiteral()))))));
3249 EXPECT_TRUE(matchAndVerifyResultTrue(
3250 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3251 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3252 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3253}
3254
Manuel Klimekba46fc02013-07-19 11:50:54 +00003255TEST(ForEachConstructorInitializer, MatchesInitializers) {
3256 EXPECT_TRUE(matches(
3257 "struct X { X() : i(42), j(42) {} int i, j; };",
3258 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3259}
3260
Daniel Jasper87c3d362012-09-20 14:12:57 +00003261TEST(ExceptionHandling, SimpleCases) {
3262 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3263 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3264 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3265 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3266 throwExpr()));
3267 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3268 throwExpr()));
3269}
3270
Manuel Klimek04616e42012-07-06 05:48:52 +00003271TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3272 EXPECT_TRUE(notMatches(
3273 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003274 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003275 EXPECT_TRUE(notMatches(
3276 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003277 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003278}
3279
3280TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3281 EXPECT_TRUE(matches(
3282 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003283 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003284}
3285
3286TEST(ForEach, BindsOneNode) {
3287 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003288 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003289 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003290}
3291
3292TEST(ForEach, BindsMultipleNodes) {
3293 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003294 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003295 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003296}
3297
3298TEST(ForEach, BindsRecursiveCombinations) {
3299 EXPECT_TRUE(matchAndVerifyResultTrue(
3300 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003301 recordDecl(hasName("C"),
3302 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003303 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003304}
3305
3306TEST(ForEachDescendant, BindsOneNode) {
3307 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003308 recordDecl(hasName("C"),
3309 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003310 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003311}
3312
Daniel Jasper94a56852012-11-16 18:39:22 +00003313TEST(ForEachDescendant, NestedForEachDescendant) {
3314 DeclarationMatcher m = recordDecl(
3315 isDefinition(), decl().bind("x"), hasName("C"));
3316 EXPECT_TRUE(matchAndVerifyResultTrue(
3317 "class A { class B { class C {}; }; };",
3318 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3319 new VerifyIdIsBoundTo<Decl>("x", "C")));
3320
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003321 // Check that a partial match of 'm' that binds 'x' in the
3322 // first part of anyOf(m, anything()) will not overwrite the
3323 // binding created by the earlier binding in the hasDescendant.
3324 EXPECT_TRUE(matchAndVerifyResultTrue(
3325 "class A { class B { class C {}; }; };",
3326 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3327 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003328}
3329
Manuel Klimek04616e42012-07-06 05:48:52 +00003330TEST(ForEachDescendant, BindsMultipleNodes) {
3331 EXPECT_TRUE(matchAndVerifyResultTrue(
3332 "class C { class D { int x; int y; }; "
3333 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003334 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003335 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003336}
3337
3338TEST(ForEachDescendant, BindsRecursiveCombinations) {
3339 EXPECT_TRUE(matchAndVerifyResultTrue(
3340 "class C { class D { "
3341 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003342 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3343 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003344 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003345}
3346
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003347TEST(ForEachDescendant, BindsCombinations) {
3348 EXPECT_TRUE(matchAndVerifyResultTrue(
3349 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3350 "(true) {} }",
3351 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3352 forEachDescendant(whileStmt().bind("while"))),
3353 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3354}
3355
3356TEST(Has, DoesNotDeleteBindings) {
3357 EXPECT_TRUE(matchAndVerifyResultTrue(
3358 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3359 new VerifyIdIsBoundTo<Decl>("x", 1)));
3360}
3361
3362TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3363 // Those matchers cover all the cases where an inner matcher is called
3364 // and there is not a 1:1 relationship between the match of the outer
3365 // matcher and the match of the inner matcher.
3366 // The pattern to look for is:
3367 // ... return InnerMatcher.matches(...); ...
3368 // In which case no special handling is needed.
3369 //
3370 // On the other hand, if there are multiple alternative matches
3371 // (for example forEach*) or matches might be discarded (for example has*)
3372 // the implementation must make sure that the discarded matches do not
3373 // affect the bindings.
3374 // When new such matchers are added, add a test here that:
3375 // - matches a simple node, and binds it as the first thing in the matcher:
3376 // recordDecl(decl().bind("x"), hasName("X")))
3377 // - uses the matcher under test afterwards in a way that not the first
3378 // alternative is matched; for anyOf, that means the first branch
3379 // would need to return false; for hasAncestor, it means that not
3380 // the direct parent matches the inner matcher.
3381
3382 EXPECT_TRUE(matchAndVerifyResultTrue(
3383 "class X { int y; };",
3384 recordDecl(
3385 recordDecl().bind("x"), hasName("::X"),
3386 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3387 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3388 EXPECT_TRUE(matchAndVerifyResultTrue(
3389 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3390 anyOf(unless(anything()), anything())),
3391 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3392 EXPECT_TRUE(matchAndVerifyResultTrue(
3393 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3394 classTemplateSpecializationDecl(
3395 decl().bind("x"),
3396 hasAnyTemplateArgument(refersToType(asString("int")))),
3397 new VerifyIdIsBoundTo<Decl>("x", 1)));
3398 EXPECT_TRUE(matchAndVerifyResultTrue(
3399 "class X { void f(); void g(); };",
3400 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3401 new VerifyIdIsBoundTo<Decl>("x", 1)));
3402 EXPECT_TRUE(matchAndVerifyResultTrue(
3403 "class X { X() : a(1), b(2) {} double a; int b; };",
3404 recordDecl(decl().bind("x"),
3405 has(constructorDecl(
3406 hasAnyConstructorInitializer(forField(hasName("b")))))),
3407 new VerifyIdIsBoundTo<Decl>("x", 1)));
3408 EXPECT_TRUE(matchAndVerifyResultTrue(
3409 "void x(int, int) { x(0, 42); }",
3410 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3411 new VerifyIdIsBoundTo<Expr>("x", 1)));
3412 EXPECT_TRUE(matchAndVerifyResultTrue(
3413 "void x(int, int y) {}",
3414 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3415 new VerifyIdIsBoundTo<Decl>("x", 1)));
3416 EXPECT_TRUE(matchAndVerifyResultTrue(
3417 "void x() { return; if (true) {} }",
3418 functionDecl(decl().bind("x"),
3419 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3420 new VerifyIdIsBoundTo<Decl>("x", 1)));
3421 EXPECT_TRUE(matchAndVerifyResultTrue(
3422 "namespace X { void b(int); void b(); }"
3423 "using X::b;",
3424 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3425 functionDecl(parameterCountIs(1))))),
3426 new VerifyIdIsBoundTo<Decl>("x", 1)));
3427 EXPECT_TRUE(matchAndVerifyResultTrue(
3428 "class A{}; class B{}; class C : B, A {};",
3429 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3430 new VerifyIdIsBoundTo<Decl>("x", 1)));
3431 EXPECT_TRUE(matchAndVerifyResultTrue(
3432 "class A{}; typedef A B; typedef A C; typedef A D;"
3433 "class E : A {};",
3434 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3435 new VerifyIdIsBoundTo<Decl>("x", 1)));
3436 EXPECT_TRUE(matchAndVerifyResultTrue(
3437 "class A { class B { void f() {} }; };",
3438 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3439 new VerifyIdIsBoundTo<Decl>("x", 1)));
3440 EXPECT_TRUE(matchAndVerifyResultTrue(
3441 "template <typename T> struct A { struct B {"
3442 " void f() { if(true) {} }"
3443 "}; };"
3444 "void t() { A<int>::B b; b.f(); }",
3445 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3446 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3447 EXPECT_TRUE(matchAndVerifyResultTrue(
3448 "class A {};",
3449 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3450 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003451 EXPECT_TRUE(matchAndVerifyResultTrue(
3452 "class A { A() : s(), i(42) {} const char *s; int i; };",
3453 constructorDecl(hasName("::A::A"), decl().bind("x"),
3454 forEachConstructorInitializer(forField(hasName("i")))),
3455 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003456}
3457
Daniel Jasper33806cd2012-11-11 22:14:55 +00003458TEST(ForEachDescendant, BindsCorrectNodes) {
3459 EXPECT_TRUE(matchAndVerifyResultTrue(
3460 "class C { void f(); int i; };",
3461 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3462 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3463 EXPECT_TRUE(matchAndVerifyResultTrue(
3464 "class C { void f() {} int i; };",
3465 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3466 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3467}
3468
Manuel Klimekabf43712013-02-04 10:59:20 +00003469TEST(FindAll, BindsNodeOnMatch) {
3470 EXPECT_TRUE(matchAndVerifyResultTrue(
3471 "class A {};",
3472 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3473 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3474}
3475
3476TEST(FindAll, BindsDescendantNodeOnMatch) {
3477 EXPECT_TRUE(matchAndVerifyResultTrue(
3478 "class A { int a; int b; };",
3479 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3480 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3481}
3482
3483TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3484 EXPECT_TRUE(matchAndVerifyResultTrue(
3485 "class A { int a; int b; };",
3486 recordDecl(hasName("::A"),
3487 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3488 fieldDecl().bind("v"))))),
3489 new VerifyIdIsBoundTo<Decl>("v", 3)));
3490
3491 EXPECT_TRUE(matchAndVerifyResultTrue(
3492 "class A { class B {}; class C {}; };",
3493 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3494 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3495}
3496
Manuel Klimek88b95872013-02-04 09:42:38 +00003497TEST(EachOf, TriggersForEachMatch) {
3498 EXPECT_TRUE(matchAndVerifyResultTrue(
3499 "class A { int a; int b; };",
3500 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3501 has(fieldDecl(hasName("b")).bind("v")))),
3502 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3503}
3504
3505TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3506 EXPECT_TRUE(matchAndVerifyResultTrue(
3507 "class A { int a; int c; };",
3508 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3509 has(fieldDecl(hasName("b")).bind("v")))),
3510 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3511 EXPECT_TRUE(matchAndVerifyResultTrue(
3512 "class A { int c; int b; };",
3513 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3514 has(fieldDecl(hasName("b")).bind("v")))),
3515 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3516 EXPECT_TRUE(notMatches(
3517 "class A { int c; int d; };",
3518 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3519 has(fieldDecl(hasName("b")).bind("v"))))));
3520}
Manuel Klimek04616e42012-07-06 05:48:52 +00003521
3522TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3523 // Make sure that we can both match the class by name (::X) and by the type
3524 // the template was instantiated with (via a field).
3525
3526 EXPECT_TRUE(matches(
3527 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003528 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003529
3530 EXPECT_TRUE(matches(
3531 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003532 recordDecl(isTemplateInstantiation(), hasDescendant(
3533 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003534}
3535
3536TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3537 EXPECT_TRUE(matches(
3538 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003539 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003540 isTemplateInstantiation())));
3541}
3542
3543TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3544 EXPECT_TRUE(matches(
3545 "template <typename T> class X { T t; }; class A {};"
3546 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003547 recordDecl(isTemplateInstantiation(), hasDescendant(
3548 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003549}
3550
3551TEST(IsTemplateInstantiation,
3552 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3553 EXPECT_TRUE(matches(
3554 "template <typename T> class X {};"
3555 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003556 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003557}
3558
3559TEST(IsTemplateInstantiation,
3560 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3561 EXPECT_TRUE(matches(
3562 "class A {};"
3563 "class X {"
3564 " template <typename U> class Y { U u; };"
3565 " Y<A> y;"
3566 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003567 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003568}
3569
3570TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3571 // FIXME: Figure out whether this makes sense. It doesn't affect the
3572 // normal use case as long as the uppermost instantiation always is marked
3573 // as template instantiation, but it might be confusing as a predicate.
3574 EXPECT_TRUE(matches(
3575 "class A {};"
3576 "template <typename T> class X {"
3577 " template <typename U> class Y { U u; };"
3578 " Y<T> y;"
3579 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003580 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003581}
3582
3583TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3584 EXPECT_TRUE(notMatches(
3585 "template <typename T> class X {}; class A {};"
3586 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003587 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003588}
3589
3590TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3591 EXPECT_TRUE(notMatches(
3592 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003593 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003594}
3595
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003596TEST(IsInstantiated, MatchesInstantiation) {
3597 EXPECT_TRUE(
3598 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3599 recordDecl(isInstantiated())));
3600}
3601
3602TEST(IsInstantiated, NotMatchesDefinition) {
3603 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3604 recordDecl(isInstantiated())));
3605}
3606
3607TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3608 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3609 "class Y { A<int> a; }; Y y;",
3610 declStmt(isInTemplateInstantiation())));
3611}
3612
3613TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3614 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3615 declStmt(isInTemplateInstantiation())));
3616}
3617
3618TEST(IsInstantiated, MatchesFunctionInstantiation) {
3619 EXPECT_TRUE(
3620 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3621 functionDecl(isInstantiated())));
3622}
3623
3624TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3625 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3626 varDecl(isInstantiated())));
3627}
3628
3629TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3630 EXPECT_TRUE(
3631 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3632 declStmt(isInTemplateInstantiation())));
3633}
3634
3635TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3636 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3637 declStmt(isInTemplateInstantiation())));
3638}
3639
3640TEST(IsInTemplateInstantiation, Sharing) {
3641 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3642 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3643 // and makes the matcher behave in non-obvious ways.
3644 EXPECT_TRUE(notMatches(
3645 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3646 Matcher));
3647 EXPECT_TRUE(matches(
3648 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3649 Matcher));
3650}
3651
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003652TEST(IsExplicitTemplateSpecialization,
3653 DoesNotMatchPrimaryTemplate) {
3654 EXPECT_TRUE(notMatches(
3655 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003656 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003657 EXPECT_TRUE(notMatches(
3658 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003659 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003660}
3661
3662TEST(IsExplicitTemplateSpecialization,
3663 DoesNotMatchExplicitTemplateInstantiations) {
3664 EXPECT_TRUE(notMatches(
3665 "template <typename T> class X {};"
3666 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003667 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003668 EXPECT_TRUE(notMatches(
3669 "template <typename T> void f(T t) {}"
3670 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003671 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003672}
3673
3674TEST(IsExplicitTemplateSpecialization,
3675 DoesNotMatchImplicitTemplateInstantiations) {
3676 EXPECT_TRUE(notMatches(
3677 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003678 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003679 EXPECT_TRUE(notMatches(
3680 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003681 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003682}
3683
3684TEST(IsExplicitTemplateSpecialization,
3685 MatchesExplicitTemplateSpecializations) {
3686 EXPECT_TRUE(matches(
3687 "template <typename T> class X {};"
3688 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003689 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003690 EXPECT_TRUE(matches(
3691 "template <typename T> void f(T t) {}"
3692 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003693 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003694}
3695
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003696TEST(HasAncenstor, MatchesDeclarationAncestors) {
3697 EXPECT_TRUE(matches(
3698 "class A { class B { class C {}; }; };",
3699 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3700}
3701
3702TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3703 EXPECT_TRUE(notMatches(
3704 "class A { class B { class C {}; }; };",
3705 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3706}
3707
3708TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3709 EXPECT_TRUE(matches(
3710 "class A { class B { void f() { C c; } class C {}; }; };",
3711 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3712 hasAncestor(recordDecl(hasName("A"))))))));
3713}
3714
3715TEST(HasAncenstor, MatchesStatementAncestors) {
3716 EXPECT_TRUE(matches(
3717 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003718 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003719}
3720
3721TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3722 EXPECT_TRUE(matches(
3723 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003724 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003725}
3726
3727TEST(HasAncestor, BindsRecursiveCombinations) {
3728 EXPECT_TRUE(matchAndVerifyResultTrue(
3729 "class C { class D { class E { class F { int y; }; }; }; };",
3730 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003731 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003732}
3733
3734TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3735 EXPECT_TRUE(matchAndVerifyResultTrue(
3736 "class C { class D { class E { class F { int y; }; }; }; };",
3737 fieldDecl(hasAncestor(
3738 decl(
3739 hasDescendant(recordDecl(isDefinition(),
3740 hasAncestor(recordDecl())))
3741 ).bind("d")
3742 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003743 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003744}
3745
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003746TEST(HasAncestor, MatchesClosestAncestor) {
3747 EXPECT_TRUE(matchAndVerifyResultTrue(
3748 "template <typename T> struct C {"
3749 " void f(int) {"
3750 " struct I { void g(T) { int x; } } i; i.g(42);"
3751 " }"
3752 "};"
3753 "template struct C<int>;",
3754 varDecl(hasName("x"),
3755 hasAncestor(functionDecl(hasParameter(
3756 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3757 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3758}
3759
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003760TEST(HasAncestor, MatchesInTemplateInstantiations) {
3761 EXPECT_TRUE(matches(
3762 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3763 "A<int>::B::C a;",
3764 fieldDecl(hasType(asString("int")),
3765 hasAncestor(recordDecl(hasName("A"))))));
3766}
3767
3768TEST(HasAncestor, MatchesInImplicitCode) {
3769 EXPECT_TRUE(matches(
3770 "struct X {}; struct A { A() {} X x; };",
3771 constructorDecl(
3772 hasAnyConstructorInitializer(withInitializer(expr(
3773 hasAncestor(recordDecl(hasName("A")))))))));
3774}
3775
Daniel Jasper632aea92012-10-22 16:26:51 +00003776TEST(HasParent, MatchesOnlyParent) {
3777 EXPECT_TRUE(matches(
3778 "void f() { if (true) { int x = 42; } }",
3779 compoundStmt(hasParent(ifStmt()))));
3780 EXPECT_TRUE(notMatches(
3781 "void f() { for (;;) { int x = 42; } }",
3782 compoundStmt(hasParent(ifStmt()))));
3783 EXPECT_TRUE(notMatches(
3784 "void f() { if (true) for (;;) { int x = 42; } }",
3785 compoundStmt(hasParent(ifStmt()))));
3786}
3787
Manuel Klimekc844a462012-12-06 14:42:48 +00003788TEST(HasAncestor, MatchesAllAncestors) {
3789 EXPECT_TRUE(matches(
3790 "template <typename T> struct C { static void f() { 42; } };"
3791 "void t() { C<int>::f(); }",
3792 integerLiteral(
3793 equals(42),
3794 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3795 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3796}
3797
3798TEST(HasParent, MatchesAllParents) {
3799 EXPECT_TRUE(matches(
3800 "template <typename T> struct C { static void f() { 42; } };"
3801 "void t() { C<int>::f(); }",
3802 integerLiteral(
3803 equals(42),
3804 hasParent(compoundStmt(hasParent(functionDecl(
3805 hasParent(recordDecl(isTemplateInstantiation())))))))));
3806 EXPECT_TRUE(matches(
3807 "template <typename T> struct C { static void f() { 42; } };"
3808 "void t() { C<int>::f(); }",
3809 integerLiteral(
3810 equals(42),
3811 hasParent(compoundStmt(hasParent(functionDecl(
3812 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3813 EXPECT_TRUE(matches(
3814 "template <typename T> struct C { static void f() { 42; } };"
3815 "void t() { C<int>::f(); }",
3816 integerLiteral(equals(42),
3817 hasParent(compoundStmt(allOf(
3818 hasParent(functionDecl(
3819 hasParent(recordDecl(isTemplateInstantiation())))),
3820 hasParent(functionDecl(hasParent(recordDecl(
3821 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003822 EXPECT_TRUE(
3823 notMatches("template <typename T> struct C { static void f() {} };"
3824 "void t() { C<int>::f(); }",
3825 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003826}
3827
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003828TEST(HasParent, NoDuplicateParents) {
3829 class HasDuplicateParents : public BoundNodesCallback {
3830 public:
3831 bool run(const BoundNodes *Nodes) override { return false; }
3832 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3833 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3834 std::set<const void *> Parents;
3835 for (const auto &Parent : Context->getParents(*Node)) {
3836 if (!Parents.insert(Parent.getMemoizationData()).second) {
3837 return true;
3838 }
3839 }
3840 return false;
3841 }
3842 };
3843 EXPECT_FALSE(matchAndVerifyResultTrue(
3844 "template <typename T> int Foo() { return 1 + 2; }\n"
3845 "int x = Foo<int>() + Foo<unsigned>();",
3846 stmt().bind("node"), new HasDuplicateParents()));
3847}
3848
Daniel Jasper516b02e2012-10-17 08:52:59 +00003849TEST(TypeMatching, MatchesTypes) {
3850 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3851}
3852
3853TEST(TypeMatching, MatchesArrayTypes) {
3854 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3855 EXPECT_TRUE(matches("int a[42];", arrayType()));
3856 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3857
3858 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3859 arrayType(hasElementType(builtinType()))));
3860
3861 EXPECT_TRUE(matches(
3862 "int const a[] = { 2, 3 };",
3863 qualType(arrayType(hasElementType(builtinType())))));
3864 EXPECT_TRUE(matches(
3865 "int const a[] = { 2, 3 };",
3866 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3867 EXPECT_TRUE(matches(
3868 "typedef const int T; T x[] = { 1, 2 };",
3869 qualType(isConstQualified(), arrayType())));
3870
3871 EXPECT_TRUE(notMatches(
3872 "int a[] = { 2, 3 };",
3873 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3874 EXPECT_TRUE(notMatches(
3875 "int a[] = { 2, 3 };",
3876 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3877 EXPECT_TRUE(notMatches(
3878 "int const a[] = { 2, 3 };",
3879 qualType(arrayType(hasElementType(builtinType())),
3880 unless(isConstQualified()))));
3881
3882 EXPECT_TRUE(matches("int a[2];",
3883 constantArrayType(hasElementType(builtinType()))));
3884 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3885}
3886
3887TEST(TypeMatching, MatchesComplexTypes) {
3888 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3889 EXPECT_TRUE(matches(
3890 "_Complex float f;",
3891 complexType(hasElementType(builtinType()))));
3892 EXPECT_TRUE(notMatches(
3893 "_Complex float f;",
3894 complexType(hasElementType(isInteger()))));
3895}
3896
3897TEST(TypeMatching, MatchesConstantArrayTypes) {
3898 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3899 EXPECT_TRUE(notMatches(
3900 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3901 constantArrayType(hasElementType(builtinType()))));
3902
3903 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3904 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3905 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3906}
3907
3908TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3909 EXPECT_TRUE(matches(
3910 "template <typename T, int Size> class array { T data[Size]; };",
3911 dependentSizedArrayType()));
3912 EXPECT_TRUE(notMatches(
3913 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3914 dependentSizedArrayType()));
3915}
3916
3917TEST(TypeMatching, MatchesIncompleteArrayType) {
3918 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3919 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3920
3921 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3922 incompleteArrayType()));
3923}
3924
3925TEST(TypeMatching, MatchesVariableArrayType) {
3926 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3927 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3928
3929 EXPECT_TRUE(matches(
3930 "void f(int b) { int a[b]; }",
3931 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3932 varDecl(hasName("b")))))))));
3933}
3934
3935TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003936 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3937 llvm::Triple::Win32) {
3938 // FIXME: Make this work for MSVC.
3939 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003940
David Majnemer197e2102014-03-05 06:32:38 +00003941 EXPECT_TRUE(matches("_Atomic(int) i;",
3942 atomicType(hasValueType(isInteger()))));
3943 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3944 atomicType(hasValueType(isInteger()))));
3945 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003946}
3947
3948TEST(TypeMatching, MatchesAutoTypes) {
3949 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3950 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3951 autoType()));
3952
Richard Smith061f1e22013-04-30 21:23:01 +00003953 // FIXME: Matching against the type-as-written can't work here, because the
3954 // type as written was not deduced.
3955 //EXPECT_TRUE(matches("auto a = 1;",
3956 // autoType(hasDeducedType(isInteger()))));
3957 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3958 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003959}
3960
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00003961TEST(TypeMatching, MatchesFunctionTypes) {
3962 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3963 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3964}
3965
Edwin Vaneec074802013-04-01 18:33:34 +00003966TEST(TypeMatching, MatchesParenType) {
3967 EXPECT_TRUE(
3968 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3969 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3970
3971 EXPECT_TRUE(matches(
3972 "int (*ptr_to_func)(int);",
3973 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3974 EXPECT_TRUE(notMatches(
3975 "int (*ptr_to_array)[4];",
3976 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3977}
3978
Daniel Jasper516b02e2012-10-17 08:52:59 +00003979TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00003980 // FIXME: Reactive when these tests can be more specific (not matching
3981 // implicit code on certain platforms), likely when we have hasDescendant for
3982 // Types/TypeLocs.
3983 //EXPECT_TRUE(matchAndVerifyResultTrue(
3984 // "int* a;",
3985 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
3986 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
3987 //EXPECT_TRUE(matchAndVerifyResultTrue(
3988 // "int* a;",
3989 // pointerTypeLoc().bind("loc"),
3990 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003991 EXPECT_TRUE(matches(
3992 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00003993 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003994 EXPECT_TRUE(matches(
3995 "int** a;",
3996 loc(pointerType(pointee(pointerType())))));
3997 EXPECT_TRUE(matches(
3998 "int* b; int* * const a = &b;",
3999 loc(qualType(isConstQualified(), pointerType()))));
4000
4001 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004002 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4003 hasType(blockPointerType()))));
4004 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4005 hasType(memberPointerType()))));
4006 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4007 hasType(pointerType()))));
4008 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4009 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004010 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4011 hasType(lValueReferenceType()))));
4012 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4013 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004014
Daniel Jasper7943eb52012-10-17 13:35:36 +00004015 Fragment = "int *ptr;";
4016 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4017 hasType(blockPointerType()))));
4018 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4019 hasType(memberPointerType()))));
4020 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4021 hasType(pointerType()))));
4022 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4023 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004024
Daniel Jasper7943eb52012-10-17 13:35:36 +00004025 Fragment = "int a; int &ref = a;";
4026 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4027 hasType(blockPointerType()))));
4028 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4029 hasType(memberPointerType()))));
4030 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4031 hasType(pointerType()))));
4032 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4033 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004034 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4035 hasType(lValueReferenceType()))));
4036 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4037 hasType(rValueReferenceType()))));
4038
4039 Fragment = "int &&ref = 2;";
4040 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4041 hasType(blockPointerType()))));
4042 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4043 hasType(memberPointerType()))));
4044 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4045 hasType(pointerType()))));
4046 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4047 hasType(referenceType()))));
4048 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4049 hasType(lValueReferenceType()))));
4050 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4051 hasType(rValueReferenceType()))));
4052}
4053
4054TEST(TypeMatching, AutoRefTypes) {
4055 std::string Fragment = "auto a = 1;"
4056 "auto b = a;"
4057 "auto &c = a;"
4058 "auto &&d = c;"
4059 "auto &&e = 2;";
4060 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4061 hasType(referenceType()))));
4062 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4063 hasType(referenceType()))));
4064 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4065 hasType(referenceType()))));
4066 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4067 hasType(lValueReferenceType()))));
4068 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4069 hasType(rValueReferenceType()))));
4070 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4071 hasType(referenceType()))));
4072 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4073 hasType(lValueReferenceType()))));
4074 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4075 hasType(rValueReferenceType()))));
4076 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4077 hasType(referenceType()))));
4078 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4079 hasType(lValueReferenceType()))));
4080 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4081 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004082}
4083
4084TEST(TypeMatching, PointeeTypes) {
4085 EXPECT_TRUE(matches("int b; int &a = b;",
4086 referenceType(pointee(builtinType()))));
4087 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4088
4089 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004090 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004091
4092 EXPECT_TRUE(matches(
4093 "int const *A;",
4094 pointerType(pointee(isConstQualified(), builtinType()))));
4095 EXPECT_TRUE(notMatches(
4096 "int *A;",
4097 pointerType(pointee(isConstQualified(), builtinType()))));
4098}
4099
4100TEST(TypeMatching, MatchesPointersToConstTypes) {
4101 EXPECT_TRUE(matches("int b; int * const a = &b;",
4102 loc(pointerType())));
4103 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004104 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004105 EXPECT_TRUE(matches(
4106 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004107 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004108 EXPECT_TRUE(matches(
4109 "int b; const int * a = &b;",
4110 pointerType(pointee(builtinType()))));
4111}
4112
4113TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004114 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4115 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004116}
4117
Edwin Vanef901b712013-02-25 14:49:29 +00004118TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004119 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004120 templateSpecializationType()));
4121}
4122
Edwin Vaneb6eae142013-02-25 20:43:32 +00004123TEST(TypeMatching, MatchesRecordType) {
4124 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004125 EXPECT_TRUE(matches("struct S{}; S s;",
4126 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4127 EXPECT_TRUE(notMatches("int i;",
4128 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004129}
4130
4131TEST(TypeMatching, MatchesElaboratedType) {
4132 EXPECT_TRUE(matches(
4133 "namespace N {"
4134 " namespace M {"
4135 " class D {};"
4136 " }"
4137 "}"
4138 "N::M::D d;", elaboratedType()));
4139 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4140 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4141}
4142
4143TEST(ElaboratedTypeNarrowing, hasQualifier) {
4144 EXPECT_TRUE(matches(
4145 "namespace N {"
4146 " namespace M {"
4147 " class D {};"
4148 " }"
4149 "}"
4150 "N::M::D d;",
4151 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4152 EXPECT_TRUE(notMatches(
4153 "namespace M {"
4154 " class D {};"
4155 "}"
4156 "M::D d;",
4157 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004158 EXPECT_TRUE(notMatches(
4159 "struct D {"
4160 "} d;",
4161 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004162}
4163
4164TEST(ElaboratedTypeNarrowing, namesType) {
4165 EXPECT_TRUE(matches(
4166 "namespace N {"
4167 " namespace M {"
4168 " class D {};"
4169 " }"
4170 "}"
4171 "N::M::D d;",
4172 elaboratedType(elaboratedType(namesType(recordType(
4173 hasDeclaration(namedDecl(hasName("D")))))))));
4174 EXPECT_TRUE(notMatches(
4175 "namespace M {"
4176 " class D {};"
4177 "}"
4178 "M::D d;",
4179 elaboratedType(elaboratedType(namesType(typedefType())))));
4180}
4181
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004182TEST(NNS, MatchesNestedNameSpecifiers) {
4183 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4184 nestedNameSpecifier()));
4185 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4186 nestedNameSpecifier()));
4187 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4188 nestedNameSpecifier()));
4189
4190 EXPECT_TRUE(matches(
4191 "struct A { static void f() {} }; void g() { A::f(); }",
4192 nestedNameSpecifier()));
4193 EXPECT_TRUE(notMatches(
4194 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4195 nestedNameSpecifier()));
4196}
4197
Daniel Jasper87c3d362012-09-20 14:12:57 +00004198TEST(NullStatement, SimpleCases) {
4199 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4200 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4201}
4202
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004203TEST(NNS, MatchesTypes) {
4204 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4205 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4206 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4207 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4208 Matcher));
4209 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4210}
4211
4212TEST(NNS, MatchesNamespaceDecls) {
4213 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4214 specifiesNamespace(hasName("ns")));
4215 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4216 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4217 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4218}
4219
4220TEST(NNS, BindsNestedNameSpecifiers) {
4221 EXPECT_TRUE(matchAndVerifyResultTrue(
4222 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4223 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4224 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4225}
4226
4227TEST(NNS, BindsNestedNameSpecifierLocs) {
4228 EXPECT_TRUE(matchAndVerifyResultTrue(
4229 "namespace ns { struct B {}; } ns::B b;",
4230 loc(nestedNameSpecifier()).bind("loc"),
4231 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4232}
4233
4234TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4235 EXPECT_TRUE(matches(
4236 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4237 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4238 EXPECT_TRUE(matches(
4239 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004240 nestedNameSpecifierLoc(hasPrefix(
4241 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004242}
4243
Daniel Jasper6fc34332012-10-30 15:42:00 +00004244TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4245 std::string Fragment =
4246 "namespace a { struct A { struct B { struct C {}; }; }; };"
4247 "void f() { a::A::B::C c; }";
4248 EXPECT_TRUE(matches(
4249 Fragment,
4250 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4251 hasDescendant(nestedNameSpecifier(
4252 specifiesNamespace(hasName("a")))))));
4253 EXPECT_TRUE(notMatches(
4254 Fragment,
4255 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4256 has(nestedNameSpecifier(
4257 specifiesNamespace(hasName("a")))))));
4258 EXPECT_TRUE(matches(
4259 Fragment,
4260 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4261 has(nestedNameSpecifier(
4262 specifiesNamespace(hasName("a")))))));
4263
4264 // Not really useful because a NestedNameSpecifier can af at most one child,
4265 // but to complete the interface.
4266 EXPECT_TRUE(matchAndVerifyResultTrue(
4267 Fragment,
4268 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4269 forEach(nestedNameSpecifier().bind("x"))),
4270 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4271}
4272
4273TEST(NNS, NestedNameSpecifiersAsDescendants) {
4274 std::string Fragment =
4275 "namespace a { struct A { struct B { struct C {}; }; }; };"
4276 "void f() { a::A::B::C c; }";
4277 EXPECT_TRUE(matches(
4278 Fragment,
4279 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4280 asString("struct a::A")))))));
4281 EXPECT_TRUE(matchAndVerifyResultTrue(
4282 Fragment,
4283 functionDecl(hasName("f"),
4284 forEachDescendant(nestedNameSpecifier().bind("x"))),
4285 // Nested names: a, a::A and a::A::B.
4286 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4287}
4288
4289TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4290 std::string Fragment =
4291 "namespace a { struct A { struct B { struct C {}; }; }; };"
4292 "void f() { a::A::B::C c; }";
4293 EXPECT_TRUE(matches(
4294 Fragment,
4295 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4296 hasDescendant(loc(nestedNameSpecifier(
4297 specifiesNamespace(hasName("a"))))))));
4298 EXPECT_TRUE(notMatches(
4299 Fragment,
4300 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4301 has(loc(nestedNameSpecifier(
4302 specifiesNamespace(hasName("a"))))))));
4303 EXPECT_TRUE(matches(
4304 Fragment,
4305 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4306 has(loc(nestedNameSpecifier(
4307 specifiesNamespace(hasName("a"))))))));
4308
4309 EXPECT_TRUE(matchAndVerifyResultTrue(
4310 Fragment,
4311 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4312 forEach(nestedNameSpecifierLoc().bind("x"))),
4313 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4314}
4315
4316TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4317 std::string Fragment =
4318 "namespace a { struct A { struct B { struct C {}; }; }; };"
4319 "void f() { a::A::B::C c; }";
4320 EXPECT_TRUE(matches(
4321 Fragment,
4322 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4323 asString("struct a::A"))))))));
4324 EXPECT_TRUE(matchAndVerifyResultTrue(
4325 Fragment,
4326 functionDecl(hasName("f"),
4327 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4328 // Nested names: a, a::A and a::A::B.
4329 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4330}
4331
Manuel Klimek191c0932013-02-01 13:41:35 +00004332template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004333public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004334 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4335 StringRef InnerId)
4336 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004337 }
4338
Manuel Klimek191c0932013-02-01 13:41:35 +00004339 virtual bool run(const BoundNodes *Nodes) { return false; }
4340
Manuel Klimekc2687452012-10-24 14:47:44 +00004341 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4342 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004343 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4344 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004345 }
4346private:
4347 std::string Id;
4348 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004349 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004350};
4351
4352TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004353 EXPECT_TRUE(matchAndVerifyResultTrue(
4354 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4355 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004356 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4357 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004358 EXPECT_TRUE(matchAndVerifyResultFalse(
4359 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4360 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004361 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4362 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004363}
4364
4365TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004366 EXPECT_TRUE(matchAndVerifyResultTrue(
4367 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004368 new VerifyMatchOnNode<clang::Stmt>(
4369 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004370 EXPECT_TRUE(matchAndVerifyResultFalse(
4371 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004372 new VerifyMatchOnNode<clang::Stmt>(
4373 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004374}
4375
4376TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4377 EXPECT_TRUE(matchAndVerifyResultTrue(
4378 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4379 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004380 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004381 EXPECT_TRUE(matchAndVerifyResultFalse(
4382 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4383 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004384 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004385}
4386
Manuel Klimekbee08572013-02-07 12:42:10 +00004387template <typename T>
4388class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4389public:
4390 virtual bool run(const BoundNodes *Nodes) { return false; }
4391
4392 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4393 const T *Node = Nodes->getNodeAs<T>("");
4394 return verify(*Nodes, *Context, Node);
4395 }
4396
4397 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004398 // Use the original typed pointer to verify we can pass pointers to subtypes
4399 // to equalsNode.
4400 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004401 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004402 "", match(stmt(hasParent(
4403 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004404 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004405 }
4406 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004407 // Use the original typed pointer to verify we can pass pointers to subtypes
4408 // to equalsNode.
4409 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004410 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004411 "", match(decl(hasParent(
4412 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004413 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004414 }
4415};
4416
4417TEST(IsEqualTo, MatchesNodesByIdentity) {
4418 EXPECT_TRUE(matchAndVerifyResultTrue(
4419 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004420 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4421 EXPECT_TRUE(matchAndVerifyResultTrue(
4422 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4423 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004424}
4425
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004426TEST(MatchFinder, CheckProfiling) {
4427 MatchFinder::MatchFinderOptions Options;
4428 llvm::StringMap<llvm::TimeRecord> Records;
4429 Options.CheckProfiling.emplace(Records);
4430 MatchFinder Finder(std::move(Options));
4431
4432 struct NamedCallback : public MatchFinder::MatchCallback {
4433 void run(const MatchFinder::MatchResult &Result) override {}
4434 StringRef getID() const override { return "MyID"; }
4435 } Callback;
4436 Finder.addMatcher(decl(), &Callback);
4437 std::unique_ptr<FrontendActionFactory> Factory(
4438 newFrontendActionFactory(&Finder));
4439 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4440
4441 EXPECT_EQ(1u, Records.size());
4442 EXPECT_EQ("MyID", Records.begin()->getKey());
4443}
4444
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004445class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4446public:
4447 VerifyStartOfTranslationUnit() : Called(false) {}
4448 virtual void run(const MatchFinder::MatchResult &Result) {
4449 EXPECT_TRUE(Called);
4450 }
4451 virtual void onStartOfTranslationUnit() {
4452 Called = true;
4453 }
4454 bool Called;
4455};
4456
4457TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4458 MatchFinder Finder;
4459 VerifyStartOfTranslationUnit VerifyCallback;
4460 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004461 std::unique_ptr<FrontendActionFactory> Factory(
4462 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004463 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4464 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004465
4466 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004467 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004468 ASSERT_TRUE(AST.get());
4469 Finder.matchAST(AST->getASTContext());
4470 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004471}
4472
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004473class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4474public:
4475 VerifyEndOfTranslationUnit() : Called(false) {}
4476 virtual void run(const MatchFinder::MatchResult &Result) {
4477 EXPECT_FALSE(Called);
4478 }
4479 virtual void onEndOfTranslationUnit() {
4480 Called = true;
4481 }
4482 bool Called;
4483};
4484
4485TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4486 MatchFinder Finder;
4487 VerifyEndOfTranslationUnit VerifyCallback;
4488 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004489 std::unique_ptr<FrontendActionFactory> Factory(
4490 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004491 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4492 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004493
4494 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004495 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004496 ASSERT_TRUE(AST.get());
4497 Finder.matchAST(AST->getASTContext());
4498 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004499}
4500
Manuel Klimekbbb75852013-06-20 14:06:32 +00004501TEST(EqualsBoundNodeMatcher, QualType) {
4502 EXPECT_TRUE(matches(
4503 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4504 hasInitializer(ignoringParenImpCasts(
4505 hasType(qualType(equalsBoundNode("type"))))))));
4506 EXPECT_TRUE(notMatches("int i = 1.f;",
4507 varDecl(hasType(qualType().bind("type")),
4508 hasInitializer(ignoringParenImpCasts(hasType(
4509 qualType(equalsBoundNode("type"))))))));
4510}
4511
4512TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4513 EXPECT_TRUE(notMatches(
4514 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4515 hasInitializer(ignoringParenImpCasts(
4516 hasType(qualType(equalsBoundNode("type"))))))));
4517}
4518
4519TEST(EqualsBoundNodeMatcher, Stmt) {
4520 EXPECT_TRUE(
4521 matches("void f() { if(true) {} }",
4522 stmt(allOf(ifStmt().bind("if"),
4523 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4524
4525 EXPECT_TRUE(notMatches(
4526 "void f() { if(true) { if (true) {} } }",
4527 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4528}
4529
4530TEST(EqualsBoundNodeMatcher, Decl) {
4531 EXPECT_TRUE(matches(
4532 "class X { class Y {}; };",
4533 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4534 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4535
4536 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4537 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4538 has(decl(equalsBoundNode("record")))))));
4539}
4540
4541TEST(EqualsBoundNodeMatcher, Type) {
4542 EXPECT_TRUE(matches(
4543 "class X { int a; int b; };",
4544 recordDecl(
4545 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4546 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4547
4548 EXPECT_TRUE(notMatches(
4549 "class X { int a; double b; };",
4550 recordDecl(
4551 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4552 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4553}
4554
4555TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004556 EXPECT_TRUE(matchAndVerifyResultTrue(
4557 "int f() {"
4558 " if (1) {"
4559 " int i = 9;"
4560 " }"
4561 " int j = 10;"
4562 " {"
4563 " float k = 9.0;"
4564 " }"
4565 " return 0;"
4566 "}",
4567 // Look for variable declarations within functions whose type is the same
4568 // as the function return type.
4569 functionDecl(returns(qualType().bind("type")),
4570 forEachDescendant(varDecl(hasType(
4571 qualType(equalsBoundNode("type")))).bind("decl"))),
4572 // Only i and j should match, not k.
4573 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4574}
4575
4576TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4577 EXPECT_TRUE(matchAndVerifyResultTrue(
4578 "void f() {"
4579 " int x;"
4580 " double d;"
4581 " x = d + x - d + x;"
4582 "}",
4583 functionDecl(
4584 hasName("f"), forEachDescendant(varDecl().bind("d")),
4585 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4586 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4587}
4588
Manuel Klimekce68f772014-03-25 14:39:26 +00004589TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4590 EXPECT_TRUE(matchAndVerifyResultTrue(
4591 "struct StringRef { int size() const; const char* data() const; };"
4592 "void f(StringRef v) {"
4593 " v.data();"
4594 "}",
4595 memberCallExpr(
4596 callee(methodDecl(hasName("data"))),
4597 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4598 .bind("var")))),
4599 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4600 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4601 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4602 .bind("data"),
4603 new VerifyIdIsBoundTo<Expr>("data", 1)));
4604
4605 EXPECT_FALSE(matches(
4606 "struct StringRef { int size() const; const char* data() const; };"
4607 "void f(StringRef v) {"
4608 " v.data();"
4609 " v.size();"
4610 "}",
4611 memberCallExpr(
4612 callee(methodDecl(hasName("data"))),
4613 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4614 .bind("var")))),
4615 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4616 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4617 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4618 .bind("data")));
4619}
4620
Manuel Klimek04616e42012-07-06 05:48:52 +00004621} // end namespace ast_matchers
4622} // end namespace clang