blob: 54aed8f3fc162d71994b0f707d48199772ca0170 [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
Samuel Benzaquenef621f42015-02-10 14:46:45 +0000382TEST(DeclarationMatcher, translationUnitDecl) {
383 const std::string Code = "int MyVar1;\n"
384 "namespace NameSpace {\n"
385 "int MyVar2;\n"
386 "} // namespace NameSpace\n";
387 EXPECT_TRUE(matches(
388 Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
389 EXPECT_FALSE(matches(
390 Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
391 EXPECT_TRUE(matches(
392 Code,
393 varDecl(hasName("MyVar2"),
394 hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
395}
396
Manuel Klimek94ad0bf2014-09-04 08:51:06 +0000397TEST(DeclarationMatcher, LinkageSpecification) {
398 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
399 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
400}
401
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000402TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000403 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000404 EXPECT_TRUE(notMatches("class X;", ClassX));
405 EXPECT_TRUE(notMatches("class X {};", ClassX));
406}
407
408TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000409 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000410 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
411 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
412}
413
414TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
415 EXPECT_TRUE(notMatches("template<typename T> class X { };"
416 "template<> class X<int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000417 classTemplateDecl(hasName("X"),
418 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000419}
420
421TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
422 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
423 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000424 classTemplateDecl(hasName("X"),
425 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000426}
427
Daniel Jasper4e566c42012-07-12 08:50:38 +0000428TEST(AllOf, AllOverloadsWork) {
429 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000430 "struct T { };"
431 "int f(int, T*, int, int);"
432 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000433 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000434 callExpr(allOf(callee(functionDecl(hasName("f"))),
435 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000436 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000437 callExpr(allOf(callee(functionDecl(hasName("f"))),
438 hasArgument(0, declRefExpr(to(varDecl()))),
439 hasArgument(1, hasType(pointsTo(
440 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000441 EXPECT_TRUE(matches(Program,
442 callExpr(allOf(callee(functionDecl(hasName("f"))),
443 hasArgument(0, declRefExpr(to(varDecl()))),
444 hasArgument(1, hasType(pointsTo(
445 recordDecl(hasName("T"))))),
446 hasArgument(2, integerLiteral(equals(3)))))));
447 EXPECT_TRUE(matches(Program,
448 callExpr(allOf(callee(functionDecl(hasName("f"))),
449 hasArgument(0, declRefExpr(to(varDecl()))),
450 hasArgument(1, hasType(pointsTo(
451 recordDecl(hasName("T"))))),
452 hasArgument(2, integerLiteral(equals(3))),
453 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000454}
455
Manuel Klimek04616e42012-07-06 05:48:52 +0000456TEST(DeclarationMatcher, MatchAnyOf) {
457 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000458 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000459 EXPECT_TRUE(
460 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
461 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
462 EXPECT_TRUE(
463 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
464 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
465
Daniel Jasper84c763e2012-07-15 19:57:12 +0000466 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000467 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000468 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
469 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
470
Manuel Klimek04616e42012-07-06 05:48:52 +0000471 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000472 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
473 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000474 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
475 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
476 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
477 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
478 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
479 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000480
481 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
482 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
483 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
484 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Aaron Ballman8f4699a2015-07-02 14:02:41 +0000485
486 EXPECT_TRUE(
487 matches("void f() try { } catch (int) { } catch (...) { }",
488 catchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000489}
490
491TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000492 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000493 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
494 EXPECT_TRUE(matches("class X {};", HasClassX));
495
496 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000497 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000498 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
499 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
500 EXPECT_TRUE(
501 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
502}
503
504TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
505 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000506 recordDecl(
507 has(recordDecl(
508 has(recordDecl(hasName("X"))),
509 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000510 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000511 has(recordDecl(
512 has(recordDecl(hasName("A"))),
513 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000514 hasName("C"))),
515 hasName("F"));
516
517 EXPECT_TRUE(matches(
518 "class F {"
519 " class Z {"
520 " class X {};"
521 " class Y {};"
522 " };"
523 " class C {"
524 " class A {};"
525 " class B {};"
526 " };"
527 "};", Recursive));
528
529 EXPECT_TRUE(matches(
530 "class F {"
531 " class Z {"
532 " class A {};"
533 " class X {};"
534 " class Y {};"
535 " };"
536 " class C {"
537 " class X {};"
538 " class A {};"
539 " class B {};"
540 " };"
541 "};", Recursive));
542
543 EXPECT_TRUE(matches(
544 "class O1 {"
545 " class O2 {"
546 " class F {"
547 " class Z {"
548 " class A {};"
549 " class X {};"
550 " class Y {};"
551 " };"
552 " class C {"
553 " class X {};"
554 " class A {};"
555 " class B {};"
556 " };"
557 " };"
558 " };"
559 "};", Recursive));
560}
561
562TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
563 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000564 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000565 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000566 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000567 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000568 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000569 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000570 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000571 hasName("Y"))),
572 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000573 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000574 anyOf(
575 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000576 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000577 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000578 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000579 hasName("B")))))),
580 hasName("F")));
581
582 EXPECT_TRUE(matches("class F {};", Recursive));
583 EXPECT_TRUE(matches("class Z {};", Recursive));
584 EXPECT_TRUE(matches("class C {};", Recursive));
585 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
586 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
587 EXPECT_TRUE(
588 matches("class O1 { class O2 {"
589 " class M { class N { class B {}; }; }; "
590 "}; };", Recursive));
591}
592
593TEST(DeclarationMatcher, MatchNot) {
594 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000595 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000596 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000597 unless(hasName("X")));
598 EXPECT_TRUE(notMatches("", NotClassX));
599 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
600 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
601 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
602 EXPECT_TRUE(
603 notMatches("class Y {}; class Z {}; class X : public Y {};",
604 NotClassX));
605
606 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000607 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000608 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000609 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000610 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000611 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000612 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
613 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
614 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000615
616 DeclarationMatcher NamedNotRecord =
617 namedDecl(hasName("Foo"), unless(recordDecl()));
618 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
619 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000620}
621
622TEST(DeclarationMatcher, HasDescendant) {
623 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000624 recordDecl(
625 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000626 hasName("Z"));
627 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
628 EXPECT_TRUE(
629 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
630 EXPECT_TRUE(
631 matches("class Z { class A { class Y { class X {}; }; }; };",
632 ZDescendantClassX));
633 EXPECT_TRUE(
634 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
635 ZDescendantClassX));
636 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
637
638 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000639 recordDecl(
640 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000641 hasName("X"))),
642 hasName("Z"));
643 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
644 ZDescendantClassXHasClassY));
645 EXPECT_TRUE(
646 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
647 ZDescendantClassXHasClassY));
648 EXPECT_TRUE(notMatches(
649 "class Z {"
650 " class A {"
651 " class B {"
652 " class X {"
653 " class C {"
654 " class Y {};"
655 " };"
656 " };"
657 " }; "
658 " };"
659 "};", ZDescendantClassXHasClassY));
660
661 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000662 recordDecl(
663 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
664 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000665 hasName("Z"));
666 EXPECT_TRUE(
667 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
668 ZDescendantClassXDescendantClassY));
669 EXPECT_TRUE(matches(
670 "class Z {"
671 " class A {"
672 " class X {"
673 " class B {"
674 " class Y {};"
675 " };"
676 " class Y {};"
677 " };"
678 " };"
679 "};", ZDescendantClassXDescendantClassY));
680}
681
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000682TEST(DeclarationMatcher, HasDescendantMemoization) {
683 DeclarationMatcher CannotMemoize =
684 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
685 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
686}
687
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000688TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
689 auto Name = hasName("i");
690 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
691 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
692 // Matching VD first should not make a cache hit for RD.
693 EXPECT_TRUE(notMatches("void f() { int i; }",
694 decl(hasDescendant(VD), hasDescendant(RD))));
695 EXPECT_TRUE(notMatches("void f() { int i; }",
696 decl(hasDescendant(RD), hasDescendant(VD))));
697 // Not matching RD first should not make a cache hit for VD either.
698 EXPECT_TRUE(matches("void f() { int i; }",
699 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
700}
701
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000702TEST(DeclarationMatcher, HasAttr) {
703 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
704 decl(hasAttr(clang::attr::WarnUnused))));
705 EXPECT_FALSE(matches("struct X {};",
706 decl(hasAttr(clang::attr::WarnUnused))));
707}
708
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000709TEST(DeclarationMatcher, MatchCudaDecl) {
710 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
711 "void g() { f<<<1, 2>>>(); }",
712 CUDAKernelCallExpr()));
713 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000714 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000715 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000716 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000717 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000718 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000719}
720
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000721// Implements a run method that returns whether BoundNodes contains a
722// Decl bound to Id that can be dynamically cast to T.
723// Optionally checks that the check succeeded a specific number of times.
724template <typename T>
725class VerifyIdIsBoundTo : public BoundNodesCallback {
726public:
727 // Create an object that checks that a node of type \c T was bound to \c Id.
728 // Does not check for a certain number of matches.
729 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
730 : Id(Id), ExpectedCount(-1), Count(0) {}
731
732 // Create an object that checks that a node of type \c T was bound to \c Id.
733 // Checks that there were exactly \c ExpectedCount matches.
734 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
735 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
736
737 // Create an object that checks that a node of type \c T was bound to \c Id.
738 // Checks that there was exactly one match with the name \c ExpectedName.
739 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000740 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
741 int ExpectedCount = 1)
742 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
743 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000744
Craig Toppera798a9d2014-03-02 09:32:10 +0000745 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000746 if (ExpectedCount != -1)
747 EXPECT_EQ(ExpectedCount, Count);
748 if (!ExpectedName.empty())
749 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000750 Count = 0;
751 Name.clear();
752 }
753
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000754 ~VerifyIdIsBoundTo() override {
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000755 EXPECT_EQ(0, Count);
756 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000757 }
758
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000759 bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000760 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000761 if (Nodes->getNodeAs<T>(Id)) {
762 ++Count;
763 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
764 Name = Named->getNameAsString();
765 } else if (const NestedNameSpecifier *NNS =
766 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
767 llvm::raw_string_ostream OS(Name);
768 NNS->print(OS, PrintingPolicy(LangOptions()));
769 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000770 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
771 EXPECT_NE(M.end(), I);
772 if (I != M.end())
773 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000774 return true;
775 }
Craig Topper416fa342014-06-08 08:38:12 +0000776 EXPECT_TRUE(M.count(Id) == 0 ||
777 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000778 return false;
779 }
780
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000781 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000782 return run(Nodes);
783 }
784
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000785private:
786 const std::string Id;
787 const int ExpectedCount;
788 int Count;
789 const std::string ExpectedName;
790 std::string Name;
791};
792
793TEST(HasDescendant, MatchesDescendantTypes) {
794 EXPECT_TRUE(matches("void f() { int i = 3; }",
795 decl(hasDescendant(loc(builtinType())))));
796 EXPECT_TRUE(matches("void f() { int i = 3; }",
797 stmt(hasDescendant(builtinType()))));
798
799 EXPECT_TRUE(matches("void f() { int i = 3; }",
800 stmt(hasDescendant(loc(builtinType())))));
801 EXPECT_TRUE(matches("void f() { int i = 3; }",
802 stmt(hasDescendant(qualType(builtinType())))));
803
804 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
805 stmt(hasDescendant(isInteger()))));
806
807 EXPECT_TRUE(matchAndVerifyResultTrue(
808 "void f() { int a; float c; int d; int e; }",
809 functionDecl(forEachDescendant(
810 varDecl(hasDescendant(isInteger())).bind("x"))),
811 new VerifyIdIsBoundTo<Decl>("x", 3)));
812}
813
814TEST(HasDescendant, MatchesDescendantsOfTypes) {
815 EXPECT_TRUE(matches("void f() { int*** i; }",
816 qualType(hasDescendant(builtinType()))));
817 EXPECT_TRUE(matches("void f() { int*** i; }",
818 qualType(hasDescendant(
819 pointerType(pointee(builtinType()))))));
820 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000821 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000822
823 EXPECT_TRUE(matchAndVerifyResultTrue(
824 "void f() { int*** i; }",
825 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
826 new VerifyIdIsBoundTo<Type>("x", 2)));
827}
828
829TEST(Has, MatchesChildrenOfTypes) {
830 EXPECT_TRUE(matches("int i;",
831 varDecl(hasName("i"), has(isInteger()))));
832 EXPECT_TRUE(notMatches("int** i;",
833 varDecl(hasName("i"), has(isInteger()))));
834 EXPECT_TRUE(matchAndVerifyResultTrue(
835 "int (*f)(float, int);",
836 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
837 new VerifyIdIsBoundTo<QualType>("x", 2)));
838}
839
840TEST(Has, MatchesChildTypes) {
841 EXPECT_TRUE(matches(
842 "int* i;",
843 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
844 EXPECT_TRUE(notMatches(
845 "int* i;",
846 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
847}
848
Samuel Benzaquenc640ef52014-10-28 13:33:58 +0000849TEST(ValueDecl, Matches) {
850 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
851 valueDecl(hasType(asString("enum EnumType")))));
852 EXPECT_TRUE(matches("void FunctionDecl();",
853 valueDecl(hasType(asString("void (void)")))));
854}
855
Daniel Jasper1dad1832012-07-10 20:20:19 +0000856TEST(Enum, DoesNotMatchClasses) {
857 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
858}
859
860TEST(Enum, MatchesEnums) {
861 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
862}
863
864TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000865 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000866 EXPECT_TRUE(matches("enum X{ A };", Matcher));
867 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
868 EXPECT_TRUE(notMatches("enum X {};", Matcher));
869}
870
Manuel Klimek04616e42012-07-06 05:48:52 +0000871TEST(StatementMatcher, Has) {
872 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000873 expr(hasType(pointsTo(recordDecl(hasName("X")))),
874 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000875
876 EXPECT_TRUE(matches(
877 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
878 EXPECT_TRUE(notMatches(
879 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
880}
881
882TEST(StatementMatcher, HasDescendant) {
883 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000884 expr(hasType(pointsTo(recordDecl(hasName("X")))),
885 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000886
887 EXPECT_TRUE(matches(
888 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
889 HasDescendantVariableI));
890 EXPECT_TRUE(notMatches(
891 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
892 HasDescendantVariableI));
893}
894
895TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000896 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000897
898 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
899 EXPECT_TRUE(notMatches("class A {};", TypeA));
900
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000901 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000902
903 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
904 TypeDerivedFromA));
905 EXPECT_TRUE(notMatches("class A {};", TypeA));
906
907 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000908 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000909
910 EXPECT_TRUE(
911 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
912}
913
Manuel Klimek04616e42012-07-06 05:48:52 +0000914TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000915 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000916
917 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000918 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000919
920 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000921 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000922
923 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000924 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000925
926 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
927 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000928 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000929
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000930 StatementMatcher MethodX =
931 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000932
933 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
934 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000935 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000936}
937
938TEST(Matcher, BindTheSameNameInAlternatives) {
939 StatementMatcher matcher = anyOf(
940 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000941 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000942 hasRHS(integerLiteral(equals(0)))),
943 binaryOperator(hasOperatorName("+"),
944 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000945 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000946
947 EXPECT_TRUE(matchAndVerifyResultTrue(
948 // The first branch of the matcher binds x to 0 but then fails.
949 // The second branch binds x to f() and succeeds.
950 "int f() { return 0 + f(); }",
951 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000952 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000953}
954
Manuel Klimekfdf98762012-08-30 19:41:06 +0000955TEST(Matcher, BindsIDForMemoizedResults) {
956 // Using the same matcher in two match expressions will make memoization
957 // kick in.
958 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
959 EXPECT_TRUE(matchAndVerifyResultTrue(
960 "class A { class B { class X {}; }; };",
961 DeclarationMatcher(anyOf(
962 recordDecl(hasName("A"), hasDescendant(ClassX)),
963 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000964 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000965}
966
Daniel Jasper856194d02012-12-03 15:43:25 +0000967TEST(HasDeclaration, HasDeclarationOfEnumType) {
968 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
969 expr(hasType(pointsTo(
970 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
971}
972
Edwin Vaneed936452013-02-25 14:32:42 +0000973TEST(HasDeclaration, HasGetDeclTraitTest) {
974 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
975 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
976 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
977}
978
Edwin Vane2c197e02013-02-19 17:14:34 +0000979TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
980 EXPECT_TRUE(matches("typedef int X; X a;",
981 varDecl(hasName("a"),
982 hasType(typedefType(hasDeclaration(decl()))))));
983
984 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
985}
986
Edwin Vanef901b712013-02-25 14:49:29 +0000987TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
988 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
989 varDecl(hasType(templateSpecializationType(
990 hasDeclaration(namedDecl(hasName("A"))))))));
991}
992
Manuel Klimek04616e42012-07-06 05:48:52 +0000993TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000994 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000995 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000996 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000997 EXPECT_TRUE(
998 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000999 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001000 EXPECT_TRUE(
1001 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001002 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001003}
1004
1005TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001006 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001007 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001008 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001009 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001010 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001011 EXPECT_TRUE(
1012 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001013 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001014}
1015
1016TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001017 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001018 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001019 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001020 EXPECT_TRUE(
1021 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001022 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001023}
1024
1025TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001026 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001027 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001028 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001029 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001030 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001031}
1032
Manuel Klimekc16c6522013-06-20 13:08:29 +00001033TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1034 EXPECT_TRUE(matches("int x;",
1035 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1036
1037 // Make sure we don't crash on implicit constructors.
1038 EXPECT_TRUE(notMatches("class X {}; X x;",
1039 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1040}
1041
Manuel Klimek04616e42012-07-06 05:48:52 +00001042TEST(Matcher, Call) {
1043 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001044 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001045 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001046
1047 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1048 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1049
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001050 StatementMatcher MethodOnY =
1051 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001052
1053 EXPECT_TRUE(
1054 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1055 MethodOnY));
1056 EXPECT_TRUE(
1057 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1058 MethodOnY));
1059 EXPECT_TRUE(
1060 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1061 MethodOnY));
1062 EXPECT_TRUE(
1063 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1064 MethodOnY));
1065 EXPECT_TRUE(
1066 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1067 MethodOnY));
1068
1069 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001070 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001071
1072 EXPECT_TRUE(
1073 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1074 MethodOnYPointer));
1075 EXPECT_TRUE(
1076 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1077 MethodOnYPointer));
1078 EXPECT_TRUE(
1079 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1080 MethodOnYPointer));
1081 EXPECT_TRUE(
1082 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1083 MethodOnYPointer));
1084 EXPECT_TRUE(
1085 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1086 MethodOnYPointer));
1087}
1088
Daniel Jasper5901e472012-10-01 13:40:41 +00001089TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001090 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001091 lambdaExpr()));
1092}
1093
1094TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001095 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1096 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001097 forRangeStmt()));
1098 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1099 forRangeStmt()));
1100}
1101
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001102TEST(Matcher, SubstNonTypeTemplateParm) {
1103 EXPECT_FALSE(matches("template<int N>\n"
1104 "struct A { static const int n = 0; };\n"
1105 "struct B : public A<42> {};",
1106 substNonTypeTemplateParmExpr()));
1107 EXPECT_TRUE(matches("template<int N>\n"
1108 "struct A { static const int n = N; };\n"
1109 "struct B : public A<42> {};",
1110 substNonTypeTemplateParmExpr()));
1111}
1112
Daniel Jasper5901e472012-10-01 13:40:41 +00001113TEST(Matcher, UserDefinedLiteral) {
1114 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1115 " return i + 1;"
1116 "}"
1117 "char c = 'a'_inc;",
1118 userDefinedLiteral()));
1119}
1120
Daniel Jasper87c3d362012-09-20 14:12:57 +00001121TEST(Matcher, FlowControl) {
1122 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1123 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1124 continueStmt()));
1125 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1126 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1127 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1128}
1129
Daniel Jasper1dad1832012-07-10 20:20:19 +00001130TEST(HasType, MatchesAsString) {
1131 EXPECT_TRUE(
1132 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001133 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001134 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001135 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001136 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001137 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001138 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001139 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001140}
1141
Manuel Klimek04616e42012-07-06 05:48:52 +00001142TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001143 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001144 // Unary operator
1145 EXPECT_TRUE(matches("class Y { }; "
1146 "bool operator!(Y x) { return false; }; "
1147 "Y y; bool c = !y;", OpCall));
1148 // No match -- special operators like "new", "delete"
1149 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1150 // we need to figure out include paths in the test.
1151 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1152 // "class Y { }; "
1153 // "void *operator new(size_t size) { return 0; } "
1154 // "Y *y = new Y;", OpCall));
1155 EXPECT_TRUE(notMatches("class Y { }; "
1156 "void operator delete(void *p) { } "
1157 "void a() {Y *y = new Y; delete y;}", OpCall));
1158 // Binary operator
1159 EXPECT_TRUE(matches("class Y { }; "
1160 "bool operator&&(Y x, Y y) { return true; }; "
1161 "Y a; Y b; bool c = a && b;",
1162 OpCall));
1163 // No match -- normal operator, not an overloaded one.
1164 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1165 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1166}
1167
1168TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1169 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001170 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001171 EXPECT_TRUE(matches("class Y { }; "
1172 "bool operator&&(Y x, Y y) { return true; }; "
1173 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1174 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001175 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001176 EXPECT_TRUE(notMatches("class Y { }; "
1177 "bool operator&&(Y x, Y y) { return true; }; "
1178 "Y a; Y b; bool c = a && b;",
1179 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001180 StatementMatcher OpStarCall =
1181 operatorCallExpr(hasOverloadedOperatorName("*"));
1182 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1183 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001184 DeclarationMatcher ClassWithOpStar =
1185 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1186 EXPECT_TRUE(matches("class Y { int operator*(); };",
1187 ClassWithOpStar));
1188 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1189 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001190 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1191 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1192 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001193}
1194
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001195TEST(Matcher, NestedOverloadedOperatorCalls) {
1196 EXPECT_TRUE(matchAndVerifyResultTrue(
1197 "class Y { }; "
1198 "Y& operator&&(Y& x, Y& y) { return x; }; "
1199 "Y a; Y b; Y c; Y d = a && b && c;",
1200 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1201 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1202 EXPECT_TRUE(matches(
1203 "class Y { }; "
1204 "Y& operator&&(Y& x, Y& y) { return x; }; "
1205 "Y a; Y b; Y c; Y d = a && b && c;",
1206 operatorCallExpr(hasParent(operatorCallExpr()))));
1207 EXPECT_TRUE(matches(
1208 "class Y { }; "
1209 "Y& operator&&(Y& x, Y& y) { return x; }; "
1210 "Y a; Y b; Y c; Y d = a && b && c;",
1211 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1212}
1213
Manuel Klimek04616e42012-07-06 05:48:52 +00001214TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001215 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001216 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001217
1218 EXPECT_TRUE(
1219 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1220 MethodOnY));
1221 EXPECT_TRUE(
1222 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1223 MethodOnY));
1224 EXPECT_TRUE(
1225 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1226 MethodOnY));
1227 EXPECT_TRUE(
1228 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1229 MethodOnY));
1230 EXPECT_TRUE(
1231 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1232 MethodOnY));
1233
1234 EXPECT_TRUE(matches(
1235 "class Y {"
1236 " public: virtual void x();"
1237 "};"
1238 "class X : public Y {"
1239 " public: virtual void x();"
1240 "};"
1241 "void z() { X *x; x->Y::x(); }", MethodOnY));
1242}
1243
1244TEST(Matcher, VariableUsage) {
1245 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001246 declRefExpr(to(
1247 varDecl(hasInitializer(
1248 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001249
1250 EXPECT_TRUE(matches(
1251 "class Y {"
1252 " public:"
1253 " bool x() const;"
1254 "};"
1255 "void z(const Y &y) {"
1256 " bool b = y.x();"
1257 " if (b) {}"
1258 "}", Reference));
1259
1260 EXPECT_TRUE(notMatches(
1261 "class Y {"
1262 " public:"
1263 " bool x() const;"
1264 "};"
1265 "void z(const Y &y) {"
1266 " bool b = y.x();"
1267 "}", Reference));
1268}
1269
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001270TEST(Matcher, VarDecl_Storage) {
1271 auto M = varDecl(hasName("X"), hasLocalStorage());
1272 EXPECT_TRUE(matches("void f() { int X; }", M));
1273 EXPECT_TRUE(notMatches("int X;", M));
1274 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1275
1276 M = varDecl(hasName("X"), hasGlobalStorage());
1277 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1278 EXPECT_TRUE(matches("int X;", M));
1279 EXPECT_TRUE(matches("void f() { static int X; }", M));
1280}
1281
Manuel Klimek61379422012-12-04 14:42:08 +00001282TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001283 EXPECT_TRUE(matches(
1284 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001285 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001286}
1287
Manuel Klimek04616e42012-07-06 05:48:52 +00001288TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001289 StatementMatcher CallOnVariableY =
1290 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001291
1292 EXPECT_TRUE(matches(
1293 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1294 EXPECT_TRUE(matches(
1295 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1296 EXPECT_TRUE(matches(
1297 "class Y { public: void x(); };"
1298 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1299 EXPECT_TRUE(matches(
1300 "class Y { public: void x(); };"
1301 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1302 EXPECT_TRUE(notMatches(
1303 "class Y { public: void x(); };"
1304 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1305 CallOnVariableY));
1306}
1307
Daniel Jasper1dad1832012-07-10 20:20:19 +00001308TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1309 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1310 unaryExprOrTypeTraitExpr()));
1311 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1312 alignOfExpr(anything())));
1313 // FIXME: Uncomment once alignof is enabled.
1314 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1315 // unaryExprOrTypeTraitExpr()));
1316 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1317 // sizeOfExpr()));
1318}
1319
1320TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1321 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1322 hasArgumentOfType(asString("int")))));
1323 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1324 hasArgumentOfType(asString("float")))));
1325 EXPECT_TRUE(matches(
1326 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001327 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001328 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001329 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001330}
1331
Manuel Klimek04616e42012-07-06 05:48:52 +00001332TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001333 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001334}
1335
1336TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001337 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001338}
1339
1340TEST(MemberExpression, MatchesVariable) {
1341 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001342 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001343 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001344 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001345 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001346 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001347}
1348
1349TEST(MemberExpression, MatchesStaticVariable) {
1350 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001351 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001352 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001353 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001354 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001355 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001356}
1357
Daniel Jasper4e566c42012-07-12 08:50:38 +00001358TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001359 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1360 EXPECT_TRUE(matches(
1361 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1362 callExpr(hasArgument(0, declRefExpr(
1363 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001364}
1365
1366TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001367 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001368 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001369 callExpr(hasArgument(0, declRefExpr(
1370 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001371}
1372
Manuel Klimek04616e42012-07-06 05:48:52 +00001373TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1374 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001375 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001376 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001377 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001378 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001379 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001380}
1381
1382TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1383 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001384 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001385 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001386 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001387 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001388 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001389}
1390
1391TEST(IsArrow, MatchesMemberCallsViaArrow) {
1392 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001393 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001394 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001395 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001396 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001397 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001398}
1399
1400TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001401 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001402
1403 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1404 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001405
1406 CallMethodX = callExpr(callee(conversionDecl()));
1407 EXPECT_TRUE(
1408 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1409 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1410 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001411}
1412
1413TEST(Callee, MatchesMemberExpressions) {
1414 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001415 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001416 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001417 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001418}
1419
1420TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001421 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001422
1423 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1424 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1425
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001426 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1427 llvm::Triple::Win32) {
1428 // FIXME: Make this work for MSVC.
1429 // Dependent contexts, but a non-dependent call.
1430 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1431 CallFunctionF));
1432 EXPECT_TRUE(
1433 matches("void f(); template <int N> struct S { void g() { f(); } };",
1434 CallFunctionF));
1435 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001436
1437 // Depedent calls don't match.
1438 EXPECT_TRUE(
1439 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1440 CallFunctionF));
1441 EXPECT_TRUE(
1442 notMatches("void f(int);"
1443 "template <typename T> struct S { void g(T t) { f(t); } };",
1444 CallFunctionF));
1445}
1446
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001447TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1448 EXPECT_TRUE(
1449 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001450 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001451}
1452
1453TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1454 EXPECT_TRUE(
1455 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001456 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001457}
1458
1459TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1460 EXPECT_TRUE(
1461 notMatches("void g(); template <typename T> void f(T t) {}"
1462 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001463 functionTemplateDecl(hasName("f"),
1464 hasDescendant(declRefExpr(to(
1465 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001466}
1467
Manuel Klimek04616e42012-07-06 05:48:52 +00001468TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001469 StatementMatcher CallArgumentY = callExpr(
1470 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001471
1472 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1473 EXPECT_TRUE(
1474 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1475 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1476
Daniel Jasper848cbe12012-09-18 13:09:13 +00001477 StatementMatcher WrongIndex = callExpr(
1478 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001479 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1480}
1481
1482TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001483 StatementMatcher CallArgumentY = callExpr(
1484 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001485 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1486 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1487 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1488}
1489
1490TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001491 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001492
1493 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1494 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1495 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1496}
1497
Daniel Jasper9f501292012-12-04 11:54:27 +00001498TEST(Matcher, ParameterCount) {
1499 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1500 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1501 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1502 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1503 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1504}
1505
Manuel Klimek04616e42012-07-06 05:48:52 +00001506TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001507 DeclarationMatcher ReferenceClassX = varDecl(
1508 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001509 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1510 ReferenceClassX));
1511 EXPECT_TRUE(
1512 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001513 // The match here is on the implicit copy constructor code for
1514 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001515 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001516 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1517 EXPECT_TRUE(
1518 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001519 EXPECT_TRUE(
1520 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1521}
1522
Edwin Vane0a4836e2013-03-06 17:02:57 +00001523TEST(QualType, hasCanonicalType) {
1524 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1525 "int a;"
1526 "int_ref b = a;",
1527 varDecl(hasType(qualType(referenceType())))));
1528 EXPECT_TRUE(
1529 matches("typedef int &int_ref;"
1530 "int a;"
1531 "int_ref b = a;",
1532 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1533}
1534
Edwin Vane119d3df2013-04-02 18:15:55 +00001535TEST(QualType, hasLocalQualifiers) {
1536 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1537 varDecl(hasType(hasLocalQualifiers()))));
1538 EXPECT_TRUE(matches("int *const j = nullptr;",
1539 varDecl(hasType(hasLocalQualifiers()))));
1540 EXPECT_TRUE(matches("int *volatile k;",
1541 varDecl(hasType(hasLocalQualifiers()))));
1542 EXPECT_TRUE(notMatches("int m;",
1543 varDecl(hasType(hasLocalQualifiers()))));
1544}
1545
Manuel Klimek04616e42012-07-06 05:48:52 +00001546TEST(HasParameter, CallsInnerMatcher) {
1547 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001548 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001549 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001550 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001551}
1552
1553TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1554 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001555 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001556}
1557
1558TEST(HasType, MatchesParameterVariableTypesStrictly) {
1559 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001560 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001561 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001562 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001563 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001564 methodDecl(hasParameter(0,
1565 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001566 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001567 methodDecl(hasParameter(0,
1568 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001569}
1570
1571TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1572 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001573 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001574 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001575 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001576}
1577
Daniel Jasper1dad1832012-07-10 20:20:19 +00001578TEST(Returns, MatchesReturnTypes) {
1579 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001580 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001581 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001582 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001583 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001584 functionDecl(returns(hasDeclaration(
1585 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001586}
1587
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001588TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001589 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1590 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1591 functionDecl(isExternC())));
1592 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001593}
1594
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001595TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1596 EXPECT_TRUE(
1597 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1598 EXPECT_TRUE(matches("void Func() = delete;",
1599 functionDecl(hasName("Func"), isDeleted())));
1600}
1601
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001602TEST(isConstexpr, MatchesConstexprDeclarations) {
1603 EXPECT_TRUE(matches("constexpr int foo = 42;",
1604 varDecl(hasName("foo"), isConstexpr())));
1605 EXPECT_TRUE(matches("constexpr int bar();",
1606 functionDecl(hasName("bar"), isConstexpr())));
1607}
1608
Manuel Klimek04616e42012-07-06 05:48:52 +00001609TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1610 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001611 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001612}
1613
1614TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1615 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001616 methodDecl(hasAnyParameter(hasType(pointsTo(
1617 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001618}
1619
Alp Toker8db6e7a2014-01-05 06:38:57 +00001620TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001621 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001622 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001623 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001624 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001625}
1626
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001627TEST(Matcher, MatchesClassTemplateSpecialization) {
1628 EXPECT_TRUE(matches("template<typename T> struct A {};"
1629 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001630 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001631 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001632 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001633 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001634 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001635}
1636
Manuel Klimekc16c6522013-06-20 13:08:29 +00001637TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1638 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1639 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1640}
1641
1642TEST(ParmVarDecl, MatchesParmVars) {
1643 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1644 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1645}
1646
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001647TEST(Matcher, MatchesTypeTemplateArgument) {
1648 EXPECT_TRUE(matches(
1649 "template<typename T> struct B {};"
1650 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001651 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001652 asString("int"))))));
1653}
1654
1655TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1656 EXPECT_TRUE(matches(
1657 "struct B { int next; };"
1658 "template<int(B::*next_ptr)> struct A {};"
1659 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001660 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1661 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001662
1663 EXPECT_TRUE(notMatches(
1664 "template <typename T> struct A {};"
1665 "A<int> a;",
1666 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1667 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001668
1669 EXPECT_TRUE(matches(
1670 "struct B { int next; };"
1671 "template<int(B::*next_ptr)> struct A {};"
1672 "A<&B::next> a;",
1673 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1674 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1675
1676 EXPECT_TRUE(notMatches(
1677 "template <typename T> struct A {};"
1678 "A<int> a;",
1679 templateSpecializationType(hasAnyTemplateArgument(
1680 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001681}
1682
1683TEST(Matcher, MatchesSpecificArgument) {
1684 EXPECT_TRUE(matches(
1685 "template<typename T, typename U> class A {};"
1686 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001687 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001688 1, refersToType(asString("int"))))));
1689 EXPECT_TRUE(notMatches(
1690 "template<typename T, typename U> class A {};"
1691 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001692 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001693 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001694
1695 EXPECT_TRUE(matches(
1696 "template<typename T, typename U> class A {};"
1697 "A<bool, int> a;",
1698 templateSpecializationType(hasTemplateArgument(
1699 1, refersToType(asString("int"))))));
1700 EXPECT_TRUE(notMatches(
1701 "template<typename T, typename U> class A {};"
1702 "A<int, bool> a;",
1703 templateSpecializationType(hasTemplateArgument(
1704 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001705}
1706
Manuel Klimek7735e402014-10-09 13:06:22 +00001707TEST(TemplateArgument, Matches) {
1708 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1709 classTemplateSpecializationDecl(
1710 hasAnyTemplateArgument(templateArgument()))));
1711 EXPECT_TRUE(matches(
1712 "template<typename T> struct C {}; C<int> c;",
1713 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1714}
1715
1716TEST(TemplateArgumentCountIs, Matches) {
1717 EXPECT_TRUE(
1718 matches("template<typename T> struct C {}; C<int> c;",
1719 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1720 EXPECT_TRUE(
1721 notMatches("template<typename T> struct C {}; C<int> c;",
1722 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1723
1724 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1725 templateSpecializationType(templateArgumentCountIs(1))));
1726 EXPECT_TRUE(
1727 notMatches("template<typename T> struct C {}; C<int> c;",
1728 templateSpecializationType(templateArgumentCountIs(2))));
1729}
1730
1731TEST(IsIntegral, Matches) {
1732 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1733 classTemplateSpecializationDecl(
1734 hasAnyTemplateArgument(isIntegral()))));
1735 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1736 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1737 templateArgument(isIntegral())))));
1738}
1739
1740TEST(RefersToIntegralType, Matches) {
1741 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1742 classTemplateSpecializationDecl(
1743 hasAnyTemplateArgument(refersToIntegralType(
1744 asString("int"))))));
1745 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1746 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1747 refersToIntegralType(asString("int"))))));
1748}
1749
1750TEST(EqualsIntegralValue, Matches) {
1751 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1752 classTemplateSpecializationDecl(
1753 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1754 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1755 classTemplateSpecializationDecl(
1756 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1757 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1758 classTemplateSpecializationDecl(
1759 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1760 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1761 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1762 equalsIntegralValue("0042")))));
1763}
1764
Daniel Jasper639522c2013-02-25 12:02:08 +00001765TEST(Matcher, MatchesAccessSpecDecls) {
1766 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1767 EXPECT_TRUE(
1768 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1769 EXPECT_TRUE(
1770 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1771 EXPECT_TRUE(
1772 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1773
1774 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1775}
1776
Edwin Vane37ee1d72013-04-09 20:46:36 +00001777TEST(Matcher, MatchesVirtualMethod) {
1778 EXPECT_TRUE(matches("class X { virtual int f(); };",
1779 methodDecl(isVirtual(), hasName("::X::f"))));
1780 EXPECT_TRUE(notMatches("class X { int f(); };",
1781 methodDecl(isVirtual())));
1782}
1783
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001784TEST(Matcher, MatchesPureMethod) {
1785 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1786 methodDecl(isPure(), hasName("::X::f"))));
1787 EXPECT_TRUE(notMatches("class X { int f(); };",
1788 methodDecl(isPure())));
1789}
1790
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001791TEST(Matcher, MatchesConstMethod) {
1792 EXPECT_TRUE(matches("struct A { void foo() const; };",
1793 methodDecl(isConst())));
1794 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1795 methodDecl(isConst())));
1796}
1797
Edwin Vane37ee1d72013-04-09 20:46:36 +00001798TEST(Matcher, MatchesOverridingMethod) {
1799 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1800 "class Y : public X { int f(); };",
1801 methodDecl(isOverride(), hasName("::Y::f"))));
1802 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1803 "class Y : public X { int f(); };",
1804 methodDecl(isOverride(), hasName("::X::f"))));
1805 EXPECT_TRUE(notMatches("class X { int f(); }; "
1806 "class Y : public X { int f(); };",
1807 methodDecl(isOverride())));
1808 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1809 methodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001810 EXPECT_TRUE(
1811 matches("template <typename Base> struct Y : Base { void f() override;};",
1812 methodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001813}
1814
Manuel Klimek04616e42012-07-06 05:48:52 +00001815TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001816 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001817
1818 EXPECT_TRUE(
1819 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1820 EXPECT_TRUE(
1821 matches("class X { public: X(); }; void x() { X x = X(); }",
1822 Constructor));
1823 EXPECT_TRUE(
1824 matches("class X { public: X(int); }; void x() { X x = 0; }",
1825 Constructor));
1826 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1827}
1828
1829TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001830 StatementMatcher Constructor = constructExpr(
1831 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001832
1833 EXPECT_TRUE(
1834 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1835 Constructor));
1836 EXPECT_TRUE(
1837 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1838 Constructor));
1839 EXPECT_TRUE(
1840 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1841 Constructor));
1842 EXPECT_TRUE(
1843 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1844 Constructor));
1845
Daniel Jasper848cbe12012-09-18 13:09:13 +00001846 StatementMatcher WrongIndex = constructExpr(
1847 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001848 EXPECT_TRUE(
1849 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1850 WrongIndex));
1851}
1852
1853TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001854 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001855
1856 EXPECT_TRUE(
1857 matches("class X { public: X(int); }; void x() { X x(0); }",
1858 Constructor1Arg));
1859 EXPECT_TRUE(
1860 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1861 Constructor1Arg));
1862 EXPECT_TRUE(
1863 matches("class X { public: X(int); }; void x() { X x = 0; }",
1864 Constructor1Arg));
1865 EXPECT_TRUE(
1866 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1867 Constructor1Arg));
1868}
1869
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001870TEST(Matcher, ConstructorListInitialization) {
1871 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1872
1873 EXPECT_TRUE(
1874 matches("class X { public: X(int); }; void x() { X x{0}; }",
1875 ConstructorListInit));
1876 EXPECT_FALSE(
1877 matches("class X { public: X(int); }; void x() { X x(0); }",
1878 ConstructorListInit));
1879}
1880
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001881TEST(Matcher,ThisExpr) {
1882 EXPECT_TRUE(
1883 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1884 EXPECT_TRUE(
1885 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1886}
1887
Manuel Klimek04616e42012-07-06 05:48:52 +00001888TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001889 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001890
1891 std::string ClassString = "class string { public: string(); ~string(); }; ";
1892
1893 EXPECT_TRUE(
1894 matches(ClassString +
1895 "string GetStringByValue();"
1896 "void FunctionTakesString(string s);"
1897 "void run() { FunctionTakesString(GetStringByValue()); }",
1898 TempExpression));
1899
1900 EXPECT_TRUE(
1901 notMatches(ClassString +
1902 "string* GetStringPointer(); "
1903 "void FunctionTakesStringPtr(string* s);"
1904 "void run() {"
1905 " string* s = GetStringPointer();"
1906 " FunctionTakesStringPtr(GetStringPointer());"
1907 " FunctionTakesStringPtr(s);"
1908 "}",
1909 TempExpression));
1910
1911 EXPECT_TRUE(
1912 notMatches("class no_dtor {};"
1913 "no_dtor GetObjByValue();"
1914 "void ConsumeObj(no_dtor param);"
1915 "void run() { ConsumeObj(GetObjByValue()); }",
1916 TempExpression));
1917}
1918
Sam Panzer68a35af2012-08-24 22:04:44 +00001919TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1920 std::string ClassString =
1921 "class string { public: string(); int length(); }; ";
1922
1923 EXPECT_TRUE(
1924 matches(ClassString +
1925 "string GetStringByValue();"
1926 "void FunctionTakesString(string s);"
1927 "void run() { FunctionTakesString(GetStringByValue()); }",
1928 materializeTemporaryExpr()));
1929
1930 EXPECT_TRUE(
1931 notMatches(ClassString +
1932 "string* GetStringPointer(); "
1933 "void FunctionTakesStringPtr(string* s);"
1934 "void run() {"
1935 " string* s = GetStringPointer();"
1936 " FunctionTakesStringPtr(GetStringPointer());"
1937 " FunctionTakesStringPtr(s);"
1938 "}",
1939 materializeTemporaryExpr()));
1940
1941 EXPECT_TRUE(
1942 notMatches(ClassString +
1943 "string GetStringByValue();"
1944 "void run() { int k = GetStringByValue().length(); }",
1945 materializeTemporaryExpr()));
1946
1947 EXPECT_TRUE(
1948 notMatches(ClassString +
1949 "string GetStringByValue();"
1950 "void run() { GetStringByValue(); }",
1951 materializeTemporaryExpr()));
1952}
1953
Manuel Klimek04616e42012-07-06 05:48:52 +00001954TEST(ConstructorDeclaration, SimpleCase) {
1955 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001956 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001957 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001958 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001959}
1960
1961TEST(ConstructorDeclaration, IsImplicit) {
1962 // This one doesn't match because the constructor is not added by the
1963 // compiler (it is not needed).
1964 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001965 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001966 // The compiler added the implicit default constructor.
1967 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001968 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001969 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001970 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001971 // The compiler added an implicit assignment operator.
1972 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1973 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001974}
1975
Daniel Jasper1dad1832012-07-10 20:20:19 +00001976TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1977 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001978 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001979}
1980
1981TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001982 EXPECT_TRUE(notMatches("class Foo {};",
1983 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001984}
1985
Manuel Klimek04616e42012-07-06 05:48:52 +00001986TEST(HasAnyConstructorInitializer, SimpleCase) {
1987 EXPECT_TRUE(notMatches(
1988 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001989 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001990 EXPECT_TRUE(matches(
1991 "class Foo {"
1992 " Foo() : foo_() { }"
1993 " int foo_;"
1994 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001995 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001996}
1997
1998TEST(HasAnyConstructorInitializer, ForField) {
1999 static const char Code[] =
2000 "class Baz { };"
2001 "class Foo {"
2002 " Foo() : foo_() { }"
2003 " Baz foo_;"
2004 " Baz bar_;"
2005 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002006 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
2007 forField(hasType(recordDecl(hasName("Baz"))))))));
2008 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002009 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002010 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
2011 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002012}
2013
2014TEST(HasAnyConstructorInitializer, WithInitializer) {
2015 static const char Code[] =
2016 "class Foo {"
2017 " Foo() : foo_(0) { }"
2018 " int foo_;"
2019 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002020 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002021 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002022 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002023 withInitializer(integerLiteral(equals(1)))))));
2024}
2025
2026TEST(HasAnyConstructorInitializer, IsWritten) {
2027 static const char Code[] =
2028 "struct Bar { Bar(){} };"
2029 "class Foo {"
2030 " Foo() : foo_() { }"
2031 " Bar foo_;"
2032 " Bar bar_;"
2033 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002034 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002035 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002036 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002037 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002038 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002039 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2040}
2041
2042TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002043 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002044
2045 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2046 EXPECT_TRUE(
2047 matches("class X { public: X(); }; void x() { new X(); }", New));
2048 EXPECT_TRUE(
2049 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2050 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2051}
2052
2053TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002054 StatementMatcher New = constructExpr(
2055 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002056
2057 EXPECT_TRUE(
2058 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2059 New));
2060 EXPECT_TRUE(
2061 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2062 New));
2063 EXPECT_TRUE(
2064 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2065 New));
2066
Daniel Jasper848cbe12012-09-18 13:09:13 +00002067 StatementMatcher WrongIndex = constructExpr(
2068 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002069 EXPECT_TRUE(
2070 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2071 WrongIndex));
2072}
2073
2074TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002075 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002076
2077 EXPECT_TRUE(
2078 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2079 EXPECT_TRUE(
2080 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2081 New));
2082}
2083
Daniel Jasper1dad1832012-07-10 20:20:19 +00002084TEST(Matcher, DeleteExpression) {
2085 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002086 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002087}
2088
Manuel Klimek04616e42012-07-06 05:48:52 +00002089TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002090 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002091
2092 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2093 EXPECT_TRUE(
2094 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2095 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2096}
2097
2098TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002099 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002100 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2101 // wide string
2102 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2103 // with escaped characters
2104 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2105 // no matching -- though the data type is the same, there is no string literal
2106 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2107}
2108
2109TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002110 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002111 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2112 // wide character
2113 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2114 // wide character, Hex encoded, NOT MATCHED!
2115 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2116 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2117}
2118
2119TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002120 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002121 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2122 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2123 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2124 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2125
2126 // Non-matching cases (character literals, float and double)
2127 EXPECT_TRUE(notMatches("int i = L'a';",
2128 HasIntLiteral)); // this is actually a character
2129 // literal cast to int
2130 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2131 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2132 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2133}
2134
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002135TEST(Matcher, FloatLiterals) {
2136 StatementMatcher HasFloatLiteral = floatLiteral();
2137 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2138 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2139 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2140 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2141 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002142 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2143 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2144 EXPECT_TRUE(
2145 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002146
2147 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002148 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2149 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2150 EXPECT_TRUE(
2151 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002152}
2153
Daniel Jasper5901e472012-10-01 13:40:41 +00002154TEST(Matcher, NullPtrLiteral) {
2155 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2156}
2157
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002158TEST(Matcher, GNUNullExpr) {
2159 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2160}
2161
Daniel Jasper87c3d362012-09-20 14:12:57 +00002162TEST(Matcher, AsmStatement) {
2163 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2164}
2165
Manuel Klimek04616e42012-07-06 05:48:52 +00002166TEST(Matcher, Conditions) {
2167 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2168
2169 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2170 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2171 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2172 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2173 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2174}
2175
Manuel Klimek909b5c942014-05-27 10:04:12 +00002176TEST(IfStmt, ChildTraversalMatchers) {
2177 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2178 ifStmt(hasThen(boolLiteral(equals(true))))));
2179 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2180 ifStmt(hasThen(boolLiteral(equals(true))))));
2181 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2182 ifStmt(hasElse(boolLiteral(equals(true))))));
2183 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2184 ifStmt(hasElse(boolLiteral(equals(true))))));
2185}
2186
Manuel Klimek04616e42012-07-06 05:48:52 +00002187TEST(MatchBinaryOperator, HasOperatorName) {
2188 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2189
2190 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2191 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2192}
2193
2194TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2195 StatementMatcher OperatorTrueFalse =
2196 binaryOperator(hasLHS(boolLiteral(equals(true))),
2197 hasRHS(boolLiteral(equals(false))));
2198
2199 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2200 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2201 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2202}
2203
2204TEST(MatchBinaryOperator, HasEitherOperand) {
2205 StatementMatcher HasOperand =
2206 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2207
2208 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2209 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2210 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2211}
2212
2213TEST(Matcher, BinaryOperatorTypes) {
2214 // Integration test that verifies the AST provides all binary operators in
2215 // a way we expect.
2216 // FIXME: Operator ','
2217 EXPECT_TRUE(
2218 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2219 EXPECT_TRUE(
2220 matches("bool b; bool c = (b = true);",
2221 binaryOperator(hasOperatorName("="))));
2222 EXPECT_TRUE(
2223 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2224 EXPECT_TRUE(
2225 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2226 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2227 EXPECT_TRUE(
2228 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2229 EXPECT_TRUE(
2230 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2231 EXPECT_TRUE(
2232 matches("int i = 1; int j = (i <<= 2);",
2233 binaryOperator(hasOperatorName("<<="))));
2234 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2235 EXPECT_TRUE(
2236 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2237 EXPECT_TRUE(
2238 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2239 EXPECT_TRUE(
2240 matches("int i = 1; int j = (i >>= 2);",
2241 binaryOperator(hasOperatorName(">>="))));
2242 EXPECT_TRUE(
2243 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2244 EXPECT_TRUE(
2245 matches("int i = 42; int j = (i ^= 42);",
2246 binaryOperator(hasOperatorName("^="))));
2247 EXPECT_TRUE(
2248 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2249 EXPECT_TRUE(
2250 matches("int i = 42; int j = (i %= 42);",
2251 binaryOperator(hasOperatorName("%="))));
2252 EXPECT_TRUE(
2253 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2254 EXPECT_TRUE(
2255 matches("bool b = true && false;",
2256 binaryOperator(hasOperatorName("&&"))));
2257 EXPECT_TRUE(
2258 matches("bool b = true; bool c = (b &= false);",
2259 binaryOperator(hasOperatorName("&="))));
2260 EXPECT_TRUE(
2261 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2262 EXPECT_TRUE(
2263 matches("bool b = true || false;",
2264 binaryOperator(hasOperatorName("||"))));
2265 EXPECT_TRUE(
2266 matches("bool b = true; bool c = (b |= false);",
2267 binaryOperator(hasOperatorName("|="))));
2268 EXPECT_TRUE(
2269 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2270 EXPECT_TRUE(
2271 matches("int i = 42; int j = (i *= 23);",
2272 binaryOperator(hasOperatorName("*="))));
2273 EXPECT_TRUE(
2274 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2275 EXPECT_TRUE(
2276 matches("int i = 42; int j = (i /= 23);",
2277 binaryOperator(hasOperatorName("/="))));
2278 EXPECT_TRUE(
2279 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2280 EXPECT_TRUE(
2281 matches("int i = 42; int j = (i += 23);",
2282 binaryOperator(hasOperatorName("+="))));
2283 EXPECT_TRUE(
2284 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2285 EXPECT_TRUE(
2286 matches("int i = 42; int j = (i -= 23);",
2287 binaryOperator(hasOperatorName("-="))));
2288 EXPECT_TRUE(
2289 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2290 binaryOperator(hasOperatorName("->*"))));
2291 EXPECT_TRUE(
2292 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2293 binaryOperator(hasOperatorName(".*"))));
2294
2295 // Member expressions as operators are not supported in matches.
2296 EXPECT_TRUE(
2297 notMatches("struct A { void x(A *a) { a->x(this); } };",
2298 binaryOperator(hasOperatorName("->"))));
2299
2300 // Initializer assignments are not represented as operator equals.
2301 EXPECT_TRUE(
2302 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2303
2304 // Array indexing is not represented as operator.
2305 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2306
2307 // Overloaded operators do not match at all.
2308 EXPECT_TRUE(notMatches(
2309 "struct A { bool operator&&(const A &a) const { return false; } };"
2310 "void x() { A a, b; a && b; }",
2311 binaryOperator()));
2312}
2313
2314TEST(MatchUnaryOperator, HasOperatorName) {
2315 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2316
2317 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2318 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2319}
2320
2321TEST(MatchUnaryOperator, HasUnaryOperand) {
2322 StatementMatcher OperatorOnFalse =
2323 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2324
2325 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2326 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2327}
2328
2329TEST(Matcher, UnaryOperatorTypes) {
2330 // Integration test that verifies the AST provides all unary operators in
2331 // a way we expect.
2332 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2333 EXPECT_TRUE(
2334 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2335 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2336 EXPECT_TRUE(
2337 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2338 EXPECT_TRUE(
2339 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2340 EXPECT_TRUE(
2341 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2342 EXPECT_TRUE(
2343 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2344 EXPECT_TRUE(
2345 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2346 EXPECT_TRUE(
2347 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2348 EXPECT_TRUE(
2349 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2350
2351 // We don't match conversion operators.
2352 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2353
2354 // Function calls are not represented as operator.
2355 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2356
2357 // Overloaded operators do not match at all.
2358 // FIXME: We probably want to add that.
2359 EXPECT_TRUE(notMatches(
2360 "struct A { bool operator!() const { return false; } };"
2361 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2362}
2363
2364TEST(Matcher, ConditionalOperator) {
2365 StatementMatcher Conditional = conditionalOperator(
2366 hasCondition(boolLiteral(equals(true))),
2367 hasTrueExpression(boolLiteral(equals(false))));
2368
2369 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2370 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2371 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2372
2373 StatementMatcher ConditionalFalse = conditionalOperator(
2374 hasFalseExpression(boolLiteral(equals(false))));
2375
2376 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2377 EXPECT_TRUE(
2378 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2379}
2380
Daniel Jasper1dad1832012-07-10 20:20:19 +00002381TEST(ArraySubscriptMatchers, ArraySubscripts) {
2382 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2383 arraySubscriptExpr()));
2384 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2385 arraySubscriptExpr()));
2386}
2387
2388TEST(ArraySubscriptMatchers, ArrayIndex) {
2389 EXPECT_TRUE(matches(
2390 "int i[2]; void f() { i[1] = 1; }",
2391 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2392 EXPECT_TRUE(matches(
2393 "int i[2]; void f() { 1[i] = 1; }",
2394 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2395 EXPECT_TRUE(notMatches(
2396 "int i[2]; void f() { i[1] = 1; }",
2397 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2398}
2399
2400TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2401 EXPECT_TRUE(matches(
2402 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002403 arraySubscriptExpr(hasBase(implicitCastExpr(
2404 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002405}
2406
Manuel Klimek04616e42012-07-06 05:48:52 +00002407TEST(Matcher, HasNameSupportsNamespaces) {
2408 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002409 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002410 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002411 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002412 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002413 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002414 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002415 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002416 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002417 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002418 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002419 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002420 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002421 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002422 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002423 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002424 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002425 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002426 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002427 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002428 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002429 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002430 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002431 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002432}
2433
2434TEST(Matcher, HasNameSupportsOuterClasses) {
2435 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002436 matches("class A { class B { class C; }; };",
2437 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002438 EXPECT_TRUE(
2439 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002440 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002441 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002442 matches("class A { class B { class C; }; };",
2443 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002444 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002445 matches("class A { class B { class C; }; };",
2446 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002447 EXPECT_TRUE(
2448 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002449 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002450 EXPECT_TRUE(
2451 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002452 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002453 EXPECT_TRUE(
2454 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002455 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002456 EXPECT_TRUE(
2457 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002458 recordDecl(hasName("::C"))));
2459 EXPECT_TRUE(
2460 notMatches("class A { class B { class C; }; };",
2461 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002462 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002463 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002464 EXPECT_TRUE(
2465 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002466 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002467}
2468
2469TEST(Matcher, IsDefinition) {
2470 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002471 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002472 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2473 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2474
2475 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002476 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002477 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2478 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2479
2480 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002481 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002482 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2483 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2484}
2485
2486TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002487 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002488 ofClass(hasName("X")))));
2489
2490 EXPECT_TRUE(
2491 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2492 EXPECT_TRUE(
2493 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2494 Constructor));
2495 EXPECT_TRUE(
2496 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2497 Constructor));
2498}
2499
2500TEST(Matcher, VisitsTemplateInstantiations) {
2501 EXPECT_TRUE(matches(
2502 "class A { public: void x(); };"
2503 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002504 "void f() { B<A> b; b.y(); }",
2505 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002506
2507 EXPECT_TRUE(matches(
2508 "class A { public: void x(); };"
2509 "class C {"
2510 " public:"
2511 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2512 "};"
2513 "void f() {"
2514 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002515 "}",
2516 recordDecl(hasName("C"),
2517 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002518}
2519
Daniel Jasper1dad1832012-07-10 20:20:19 +00002520TEST(Matcher, HandlesNullQualTypes) {
2521 // FIXME: Add a Type matcher so we can replace uses of this
2522 // variable with Type(True())
2523 const TypeMatcher AnyType = anything();
2524
2525 // We don't really care whether this matcher succeeds; we're testing that
2526 // it completes without crashing.
2527 EXPECT_TRUE(matches(
2528 "struct A { };"
2529 "template <typename T>"
2530 "void f(T t) {"
2531 " T local_t(t /* this becomes a null QualType in the AST */);"
2532 "}"
2533 "void g() {"
2534 " f(0);"
2535 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002536 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002537 anyOf(
2538 TypeMatcher(hasDeclaration(anything())),
2539 pointsTo(AnyType),
2540 references(AnyType)
2541 // Other QualType matchers should go here.
2542 ))))));
2543}
2544
Manuel Klimek04616e42012-07-06 05:48:52 +00002545// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002546AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002547 // Make sure all special variables are used: node, match_finder,
2548 // bound_nodes_builder, and the parameter named 'AMatcher'.
2549 return AMatcher.matches(Node, Finder, Builder);
2550}
2551
2552TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002553 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002554
2555 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002556 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002557
2558 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002559 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002560
2561 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002562 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002563}
2564
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002565AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2566 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2567 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002568 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002569 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002570 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2571 ASTMatchFinder::BK_First);
2572}
2573
2574TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002575 DeclarationMatcher HasClassB =
2576 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002577
2578 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002579 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002580
2581 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002582 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002583
2584 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002585 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002586
2587 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002588 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002589
2590 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2591}
2592
2593TEST(For, FindsForLoops) {
2594 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2595 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002596 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2597 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002598 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002599}
2600
Daniel Jasper4e566c42012-07-12 08:50:38 +00002601TEST(For, ForLoopInternals) {
2602 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2603 forStmt(hasCondition(anything()))));
2604 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2605 forStmt(hasLoopInit(anything()))));
2606}
2607
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002608TEST(For, ForRangeLoopInternals) {
2609 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2610 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002611 EXPECT_TRUE(matches(
2612 "void f(){ int a[] {1, 2}; for (int i : a); }",
2613 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002614}
2615
Daniel Jasper4e566c42012-07-12 08:50:38 +00002616TEST(For, NegativeForLoopInternals) {
2617 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002618 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002619 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2620 forStmt(hasLoopInit(anything()))));
2621}
2622
Manuel Klimek04616e42012-07-06 05:48:52 +00002623TEST(For, ReportsNoFalsePositives) {
2624 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2625 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2626}
2627
2628TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002629 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2630 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2631 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002632}
2633
2634TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2635 // It's not a compound statement just because there's "{}" in the source
2636 // text. This is an AST search, not grep.
2637 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002638 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002639 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002640 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002641}
2642
Daniel Jasper4e566c42012-07-12 08:50:38 +00002643TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002644 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002645 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002646 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002647 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002648 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002649 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002650 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002651 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002652 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2653 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002654}
2655
2656TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2657 // The simplest case: every compound statement is in a function
2658 // definition, and the function body itself must be a compound
2659 // statement.
2660 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002661 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002662}
2663
2664TEST(HasAnySubstatement, IsNotRecursive) {
2665 // It's really "has any immediate substatement".
2666 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002667 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002668}
2669
2670TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2671 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002672 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002673}
2674
2675TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2676 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002677 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002678}
2679
2680TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2681 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002682 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002683 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002684 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002685}
2686
2687TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2688 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002689 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002690 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002691 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002692 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002693 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002694}
2695
2696TEST(StatementCountIs, WorksWithMultipleStatements) {
2697 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002698 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002699}
2700
2701TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2702 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002703 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002704 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002705 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002706 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002707 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002708 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002709 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002710}
2711
2712TEST(Member, WorksInSimplestCase) {
2713 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002714 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002715}
2716
2717TEST(Member, DoesNotMatchTheBaseExpression) {
2718 // Don't pick out the wrong part of the member expression, this should
2719 // be checking the member (name) only.
2720 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002721 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002722}
2723
2724TEST(Member, MatchesInMemberFunctionCall) {
2725 EXPECT_TRUE(matches("void f() {"
2726 " struct { void first() {}; } s;"
2727 " s.first();"
2728 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002729 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002730}
2731
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002732TEST(Member, MatchesMember) {
2733 EXPECT_TRUE(matches(
2734 "struct A { int i; }; void f() { A a; a.i = 2; }",
2735 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2736 EXPECT_TRUE(notMatches(
2737 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2738 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2739}
2740
Daniel Jasper639522c2013-02-25 12:02:08 +00002741TEST(Member, UnderstandsAccess) {
2742 EXPECT_TRUE(matches(
2743 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2744 EXPECT_TRUE(notMatches(
2745 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2746 EXPECT_TRUE(notMatches(
2747 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2748
2749 EXPECT_TRUE(notMatches(
2750 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2751 EXPECT_TRUE(notMatches(
2752 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2753 EXPECT_TRUE(matches(
2754 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2755
2756 EXPECT_TRUE(notMatches(
2757 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2758 EXPECT_TRUE(matches("class A { protected: int i; };",
2759 fieldDecl(isProtected(), hasName("i"))));
2760 EXPECT_TRUE(notMatches(
2761 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2762
2763 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2764 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2765 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2766 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2767}
2768
Dmitri Gribenko06963042012-08-18 00:29:27 +00002769TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002770 // Fails in C++11 mode
2771 EXPECT_TRUE(matchesConditionally(
2772 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2773 "class X { void *operator new(std::size_t); };",
2774 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002775
2776 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002777 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002778
Daniel Jasper5901e472012-10-01 13:40:41 +00002779 // Fails in C++11 mode
2780 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002781 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2782 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002783 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002784}
2785
Manuel Klimek04616e42012-07-06 05:48:52 +00002786TEST(HasObjectExpression, DoesNotMatchMember) {
2787 EXPECT_TRUE(notMatches(
2788 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002789 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002790}
2791
2792TEST(HasObjectExpression, MatchesBaseOfVariable) {
2793 EXPECT_TRUE(matches(
2794 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002795 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002796 EXPECT_TRUE(matches(
2797 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002798 memberExpr(hasObjectExpression(
2799 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002800}
2801
2802TEST(HasObjectExpression,
2803 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2804 EXPECT_TRUE(matches(
2805 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002806 memberExpr(hasObjectExpression(
2807 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002808 EXPECT_TRUE(matches(
2809 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002810 memberExpr(hasObjectExpression(
2811 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002812}
2813
2814TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002815 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2816 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2817 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2818 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002819}
2820
2821TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002822 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002823}
2824
2825TEST(IsConstQualified, MatchesConstInt) {
2826 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002827 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002828}
2829
2830TEST(IsConstQualified, MatchesConstPointer) {
2831 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002832 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002833}
2834
2835TEST(IsConstQualified, MatchesThroughTypedef) {
2836 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002837 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002838 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002839 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002840}
2841
2842TEST(IsConstQualified, DoesNotMatchInappropriately) {
2843 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002844 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002845 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002846 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002847}
2848
Sam Panzer80c13772012-08-16 16:58:10 +00002849TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002850 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2851 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2852 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2853 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002854}
2855TEST(CastExpression, MatchesImplicitCasts) {
2856 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002857 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002858 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002859 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002860}
2861
2862TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002863 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2864 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2865 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2866 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002867}
2868
Manuel Klimek04616e42012-07-06 05:48:52 +00002869TEST(ReinterpretCast, MatchesSimpleCase) {
2870 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002871 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002872}
2873
2874TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002875 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002876 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002877 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002878 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002879 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002880 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2881 "B b;"
2882 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002883 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002884}
2885
2886TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002887 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002888 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002889 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002890}
2891
2892TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002893 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002894 EXPECT_TRUE(
2895 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002896 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002897 EXPECT_TRUE(
2898 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002899 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002900}
2901
2902TEST(DynamicCast, MatchesSimpleCase) {
2903 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2904 "B b;"
2905 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002906 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002907}
2908
2909TEST(StaticCast, MatchesSimpleCase) {
2910 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002911 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002912}
2913
2914TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002915 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002916 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002917 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002918 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002919 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002920 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2921 "B b;"
2922 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002923 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002924}
2925
Daniel Jasper417f7762012-09-18 13:36:17 +00002926TEST(CStyleCast, MatchesSimpleCase) {
2927 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2928}
2929
2930TEST(CStyleCast, DoesNotMatchOtherCasts) {
2931 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2932 "char q, *r = const_cast<char*>(&q);"
2933 "void* s = reinterpret_cast<char*>(&s);"
2934 "struct B { virtual ~B() {} }; struct D : B {};"
2935 "B b;"
2936 "D* t = dynamic_cast<D*>(&b);",
2937 cStyleCastExpr()));
2938}
2939
Manuel Klimek04616e42012-07-06 05:48:52 +00002940TEST(HasDestinationType, MatchesSimpleCase) {
2941 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002942 staticCastExpr(hasDestinationType(
2943 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002944}
2945
Sam Panzer80c13772012-08-16 16:58:10 +00002946TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2947 // This test creates an implicit const cast.
2948 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002949 implicitCastExpr(
2950 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002951 // This test creates an implicit array-to-pointer cast.
2952 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002953 implicitCastExpr(hasImplicitDestinationType(
2954 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002955}
2956
2957TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2958 // This test creates an implicit cast from int to char.
2959 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002960 implicitCastExpr(hasImplicitDestinationType(
2961 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002962 // This test creates an implicit array-to-pointer cast.
2963 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002964 implicitCastExpr(hasImplicitDestinationType(
2965 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002966}
2967
2968TEST(ImplicitCast, MatchesSimpleCase) {
2969 // This test creates an implicit const cast.
2970 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002971 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002972 // This test creates an implicit cast from int to char.
2973 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002974 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002975 // This test creates an implicit array-to-pointer cast.
2976 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002977 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002978}
2979
2980TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002981 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002982 // are present, and that it ignores explicit and paren casts.
2983
2984 // These two test cases have no casts.
2985 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002986 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002987 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002988 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002989
2990 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002991 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002992 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002993 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002994
2995 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002996 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002997}
2998
2999TEST(IgnoringImpCasts, MatchesImpCasts) {
3000 // This test checks that ignoringImpCasts matches when implicit casts are
3001 // present and its inner matcher alone does not match.
3002 // Note that this test creates an implicit const cast.
3003 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003004 varDecl(hasInitializer(ignoringImpCasts(
3005 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003006 // This test creates an implict cast from int to char.
3007 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003008 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003009 integerLiteral(equals(0)))))));
3010}
3011
3012TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3013 // These tests verify that ignoringImpCasts does not match if the inner
3014 // matcher does not match.
3015 // Note that the first test creates an implicit const cast.
3016 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003017 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003018 unless(anything()))))));
3019 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003020 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003021 unless(anything()))))));
3022
3023 // These tests verify that ignoringImplictCasts does not look through explicit
3024 // casts or parentheses.
3025 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003026 varDecl(hasInitializer(ignoringImpCasts(
3027 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003028 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003029 varDecl(hasInitializer(ignoringImpCasts(
3030 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003031 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003032 varDecl(hasInitializer(ignoringImpCasts(
3033 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003034 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003035 varDecl(hasInitializer(ignoringImpCasts(
3036 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003037}
3038
3039TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3040 // This test verifies that expressions that do not have implicit casts
3041 // still match the inner matcher.
3042 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003043 varDecl(hasInitializer(ignoringImpCasts(
3044 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003045}
3046
3047TEST(IgnoringParenCasts, MatchesParenCasts) {
3048 // This test checks that ignoringParenCasts matches when parentheses and/or
3049 // casts are present and its inner matcher alone does not match.
3050 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003051 varDecl(hasInitializer(ignoringParenCasts(
3052 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003053 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003054 varDecl(hasInitializer(ignoringParenCasts(
3055 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003056
3057 // This test creates an implict cast from int to char in addition to the
3058 // parentheses.
3059 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003060 varDecl(hasInitializer(ignoringParenCasts(
3061 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003062
3063 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003064 varDecl(hasInitializer(ignoringParenCasts(
3065 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003066 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003067 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003068 integerLiteral(equals(0)))))));
3069}
3070
3071TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3072 // This test verifies that expressions that do not have any casts still match.
3073 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003074 varDecl(hasInitializer(ignoringParenCasts(
3075 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003076}
3077
3078TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3079 // These tests verify that ignoringImpCasts does not match if the inner
3080 // matcher does not match.
3081 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003082 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003083 unless(anything()))))));
3084
3085 // This test creates an implicit cast from int to char in addition to the
3086 // parentheses.
3087 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003088 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003089 unless(anything()))))));
3090
3091 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003092 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003093 unless(anything()))))));
3094}
3095
3096TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3097 // This test checks that ignoringParenAndImpCasts matches when
3098 // parentheses and/or implicit casts are present and its inner matcher alone
3099 // does not match.
3100 // Note that this test creates an implicit const cast.
3101 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003102 varDecl(hasInitializer(ignoringParenImpCasts(
3103 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003104 // This test creates an implicit cast from int to char.
3105 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003106 varDecl(hasInitializer(ignoringParenImpCasts(
3107 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003108}
3109
3110TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3111 // This test verifies that expressions that do not have parentheses or
3112 // implicit casts still match.
3113 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003114 varDecl(hasInitializer(ignoringParenImpCasts(
3115 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003116 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003117 varDecl(hasInitializer(ignoringParenImpCasts(
3118 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003119}
3120
3121TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3122 // These tests verify that ignoringParenImpCasts does not match if
3123 // the inner matcher does not match.
3124 // This test creates an implicit cast.
3125 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003126 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003127 unless(anything()))))));
3128 // These tests verify that ignoringParenAndImplictCasts does not look
3129 // through explicit casts.
3130 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003131 varDecl(hasInitializer(ignoringParenImpCasts(
3132 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003133 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003134 varDecl(hasInitializer(ignoringParenImpCasts(
3135 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003136 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003137 varDecl(hasInitializer(ignoringParenImpCasts(
3138 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003139}
3140
Manuel Klimeke9235692012-07-25 10:02:02 +00003141TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003142 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3143 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003144 implicitCastExpr(
3145 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003146}
3147
Manuel Klimeke9235692012-07-25 10:02:02 +00003148TEST(HasSourceExpression, MatchesExplicitCasts) {
3149 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003150 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003151 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003152 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003153}
3154
Manuel Klimek04616e42012-07-06 05:48:52 +00003155TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003156 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003157}
3158
3159TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003160 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003161}
3162
3163TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003164 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003165}
3166
3167TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003168 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003169}
3170
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003171TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3172 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3173 "const Foo f = Foo();",
3174 varDecl(hasInitializer(exprWithCleanups()))));
3175 EXPECT_FALSE(matches("struct Foo { };"
3176 "const Foo f = Foo();",
3177 varDecl(hasInitializer(exprWithCleanups()))));
3178}
3179
Daniel Jasper1dad1832012-07-10 20:20:19 +00003180TEST(InitListExpression, MatchesInitListExpression) {
3181 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3182 initListExpr(hasType(asString("int [2]")))));
3183 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003184 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003185 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3186 "void f();"
3187 "S s[1] = { &f };",
3188 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003189 EXPECT_TRUE(
3190 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003191}
3192
3193TEST(UsingDeclaration, MatchesUsingDeclarations) {
3194 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3195 usingDecl()));
3196}
3197
3198TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3199 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3200 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3201}
3202
3203TEST(UsingDeclaration, MatchesSpecificTarget) {
3204 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3205 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003206 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003207 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3208 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003209 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003210}
3211
3212TEST(UsingDeclaration, ThroughUsingDeclaration) {
3213 EXPECT_TRUE(matches(
3214 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003215 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003216 EXPECT_TRUE(notMatches(
3217 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003218 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003219}
3220
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003221TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3222 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3223 usingDirectiveDecl()));
3224 EXPECT_FALSE(
3225 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3226}
3227
Sam Panzerd624bfb2012-08-16 17:20:59 +00003228TEST(SingleDecl, IsSingleDecl) {
3229 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003230 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003231 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3232 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3233 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3234 SingleDeclStmt));
3235}
3236
3237TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003238 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003239
3240 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003241 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003242 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003243 declStmt(containsDeclaration(0, MatchesInit),
3244 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003245 unsigned WrongIndex = 42;
3246 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003247 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003248 MatchesInit))));
3249}
3250
3251TEST(DeclCount, DeclCountIsCorrect) {
3252 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003253 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003254 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003255 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003256 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003257 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003258}
3259
Manuel Klimek04616e42012-07-06 05:48:52 +00003260TEST(While, MatchesWhileLoops) {
3261 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3262 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3263 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3264}
3265
3266TEST(Do, MatchesDoLoops) {
3267 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3268 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3269}
3270
3271TEST(Do, DoesNotMatchWhileLoops) {
3272 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3273}
3274
3275TEST(SwitchCase, MatchesCase) {
3276 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3277 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3278 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3279 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3280}
3281
Daniel Jasper87c3d362012-09-20 14:12:57 +00003282TEST(SwitchCase, MatchesSwitch) {
3283 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3284 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3285 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3286 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3287}
3288
Peter Collingbourne3154a102013-05-10 11:52:02 +00003289TEST(SwitchCase, MatchesEachCase) {
3290 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3291 switchStmt(forEachSwitchCase(caseStmt()))));
3292 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3293 switchStmt(forEachSwitchCase(caseStmt()))));
3294 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3295 switchStmt(forEachSwitchCase(caseStmt()))));
3296 EXPECT_TRUE(notMatches(
3297 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3298 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3299 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3300 switchStmt(forEachSwitchCase(
3301 caseStmt(hasCaseConstant(integerLiteral()))))));
3302 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3303 switchStmt(forEachSwitchCase(
3304 caseStmt(hasCaseConstant(integerLiteral()))))));
3305 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3306 switchStmt(forEachSwitchCase(
3307 caseStmt(hasCaseConstant(integerLiteral()))))));
3308 EXPECT_TRUE(matchAndVerifyResultTrue(
3309 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3310 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3311 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3312}
3313
Manuel Klimekba46fc02013-07-19 11:50:54 +00003314TEST(ForEachConstructorInitializer, MatchesInitializers) {
3315 EXPECT_TRUE(matches(
3316 "struct X { X() : i(42), j(42) {} int i, j; };",
3317 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3318}
3319
Daniel Jasper87c3d362012-09-20 14:12:57 +00003320TEST(ExceptionHandling, SimpleCases) {
3321 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3322 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3323 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3324 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3325 throwExpr()));
3326 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3327 throwExpr()));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003328 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
3329 catchStmt(isCatchAll())));
3330 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
3331 catchStmt(isCatchAll())));
Aaron Ballman39918462015-07-15 17:11:21 +00003332 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3333 varDecl(isExceptionVariable())));
3334 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3335 varDecl(isExceptionVariable())));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003336}
3337
Manuel Klimek04616e42012-07-06 05:48:52 +00003338TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3339 EXPECT_TRUE(notMatches(
3340 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003341 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003342 EXPECT_TRUE(notMatches(
3343 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003344 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003345}
3346
3347TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3348 EXPECT_TRUE(matches(
3349 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003350 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003351}
3352
3353TEST(ForEach, BindsOneNode) {
3354 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003355 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003356 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003357}
3358
3359TEST(ForEach, BindsMultipleNodes) {
3360 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003361 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003362 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003363}
3364
3365TEST(ForEach, BindsRecursiveCombinations) {
3366 EXPECT_TRUE(matchAndVerifyResultTrue(
3367 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003368 recordDecl(hasName("C"),
3369 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003370 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003371}
3372
3373TEST(ForEachDescendant, BindsOneNode) {
3374 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003375 recordDecl(hasName("C"),
3376 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003377 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003378}
3379
Daniel Jasper94a56852012-11-16 18:39:22 +00003380TEST(ForEachDescendant, NestedForEachDescendant) {
3381 DeclarationMatcher m = recordDecl(
3382 isDefinition(), decl().bind("x"), hasName("C"));
3383 EXPECT_TRUE(matchAndVerifyResultTrue(
3384 "class A { class B { class C {}; }; };",
3385 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3386 new VerifyIdIsBoundTo<Decl>("x", "C")));
3387
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003388 // Check that a partial match of 'm' that binds 'x' in the
3389 // first part of anyOf(m, anything()) will not overwrite the
3390 // binding created by the earlier binding in the hasDescendant.
3391 EXPECT_TRUE(matchAndVerifyResultTrue(
3392 "class A { class B { class C {}; }; };",
3393 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3394 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003395}
3396
Manuel Klimek04616e42012-07-06 05:48:52 +00003397TEST(ForEachDescendant, BindsMultipleNodes) {
3398 EXPECT_TRUE(matchAndVerifyResultTrue(
3399 "class C { class D { int x; int y; }; "
3400 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003401 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003402 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003403}
3404
3405TEST(ForEachDescendant, BindsRecursiveCombinations) {
3406 EXPECT_TRUE(matchAndVerifyResultTrue(
3407 "class C { class D { "
3408 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003409 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3410 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003411 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003412}
3413
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003414TEST(ForEachDescendant, BindsCombinations) {
3415 EXPECT_TRUE(matchAndVerifyResultTrue(
3416 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3417 "(true) {} }",
3418 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3419 forEachDescendant(whileStmt().bind("while"))),
3420 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3421}
3422
3423TEST(Has, DoesNotDeleteBindings) {
3424 EXPECT_TRUE(matchAndVerifyResultTrue(
3425 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3426 new VerifyIdIsBoundTo<Decl>("x", 1)));
3427}
3428
3429TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3430 // Those matchers cover all the cases where an inner matcher is called
3431 // and there is not a 1:1 relationship between the match of the outer
3432 // matcher and the match of the inner matcher.
3433 // The pattern to look for is:
3434 // ... return InnerMatcher.matches(...); ...
3435 // In which case no special handling is needed.
3436 //
3437 // On the other hand, if there are multiple alternative matches
3438 // (for example forEach*) or matches might be discarded (for example has*)
3439 // the implementation must make sure that the discarded matches do not
3440 // affect the bindings.
3441 // When new such matchers are added, add a test here that:
3442 // - matches a simple node, and binds it as the first thing in the matcher:
3443 // recordDecl(decl().bind("x"), hasName("X")))
3444 // - uses the matcher under test afterwards in a way that not the first
3445 // alternative is matched; for anyOf, that means the first branch
3446 // would need to return false; for hasAncestor, it means that not
3447 // the direct parent matches the inner matcher.
3448
3449 EXPECT_TRUE(matchAndVerifyResultTrue(
3450 "class X { int y; };",
3451 recordDecl(
3452 recordDecl().bind("x"), hasName("::X"),
3453 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3454 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3455 EXPECT_TRUE(matchAndVerifyResultTrue(
3456 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3457 anyOf(unless(anything()), anything())),
3458 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3459 EXPECT_TRUE(matchAndVerifyResultTrue(
3460 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3461 classTemplateSpecializationDecl(
3462 decl().bind("x"),
3463 hasAnyTemplateArgument(refersToType(asString("int")))),
3464 new VerifyIdIsBoundTo<Decl>("x", 1)));
3465 EXPECT_TRUE(matchAndVerifyResultTrue(
3466 "class X { void f(); void g(); };",
3467 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3468 new VerifyIdIsBoundTo<Decl>("x", 1)));
3469 EXPECT_TRUE(matchAndVerifyResultTrue(
3470 "class X { X() : a(1), b(2) {} double a; int b; };",
3471 recordDecl(decl().bind("x"),
3472 has(constructorDecl(
3473 hasAnyConstructorInitializer(forField(hasName("b")))))),
3474 new VerifyIdIsBoundTo<Decl>("x", 1)));
3475 EXPECT_TRUE(matchAndVerifyResultTrue(
3476 "void x(int, int) { x(0, 42); }",
3477 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3478 new VerifyIdIsBoundTo<Expr>("x", 1)));
3479 EXPECT_TRUE(matchAndVerifyResultTrue(
3480 "void x(int, int y) {}",
3481 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3482 new VerifyIdIsBoundTo<Decl>("x", 1)));
3483 EXPECT_TRUE(matchAndVerifyResultTrue(
3484 "void x() { return; if (true) {} }",
3485 functionDecl(decl().bind("x"),
3486 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3487 new VerifyIdIsBoundTo<Decl>("x", 1)));
3488 EXPECT_TRUE(matchAndVerifyResultTrue(
3489 "namespace X { void b(int); void b(); }"
3490 "using X::b;",
3491 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3492 functionDecl(parameterCountIs(1))))),
3493 new VerifyIdIsBoundTo<Decl>("x", 1)));
3494 EXPECT_TRUE(matchAndVerifyResultTrue(
3495 "class A{}; class B{}; class C : B, A {};",
3496 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3497 new VerifyIdIsBoundTo<Decl>("x", 1)));
3498 EXPECT_TRUE(matchAndVerifyResultTrue(
3499 "class A{}; typedef A B; typedef A C; typedef A D;"
3500 "class E : A {};",
3501 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3502 new VerifyIdIsBoundTo<Decl>("x", 1)));
3503 EXPECT_TRUE(matchAndVerifyResultTrue(
3504 "class A { class B { void f() {} }; };",
3505 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3506 new VerifyIdIsBoundTo<Decl>("x", 1)));
3507 EXPECT_TRUE(matchAndVerifyResultTrue(
3508 "template <typename T> struct A { struct B {"
3509 " void f() { if(true) {} }"
3510 "}; };"
3511 "void t() { A<int>::B b; b.f(); }",
3512 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3513 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3514 EXPECT_TRUE(matchAndVerifyResultTrue(
3515 "class A {};",
3516 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3517 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003518 EXPECT_TRUE(matchAndVerifyResultTrue(
3519 "class A { A() : s(), i(42) {} const char *s; int i; };",
3520 constructorDecl(hasName("::A::A"), decl().bind("x"),
3521 forEachConstructorInitializer(forField(hasName("i")))),
3522 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003523}
3524
Daniel Jasper33806cd2012-11-11 22:14:55 +00003525TEST(ForEachDescendant, BindsCorrectNodes) {
3526 EXPECT_TRUE(matchAndVerifyResultTrue(
3527 "class C { void f(); int i; };",
3528 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3529 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3530 EXPECT_TRUE(matchAndVerifyResultTrue(
3531 "class C { void f() {} int i; };",
3532 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3533 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3534}
3535
Manuel Klimekabf43712013-02-04 10:59:20 +00003536TEST(FindAll, BindsNodeOnMatch) {
3537 EXPECT_TRUE(matchAndVerifyResultTrue(
3538 "class A {};",
3539 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3540 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3541}
3542
3543TEST(FindAll, BindsDescendantNodeOnMatch) {
3544 EXPECT_TRUE(matchAndVerifyResultTrue(
3545 "class A { int a; int b; };",
3546 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3547 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3548}
3549
3550TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3551 EXPECT_TRUE(matchAndVerifyResultTrue(
3552 "class A { int a; int b; };",
3553 recordDecl(hasName("::A"),
3554 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3555 fieldDecl().bind("v"))))),
3556 new VerifyIdIsBoundTo<Decl>("v", 3)));
3557
3558 EXPECT_TRUE(matchAndVerifyResultTrue(
3559 "class A { class B {}; class C {}; };",
3560 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3561 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3562}
3563
Manuel Klimek88b95872013-02-04 09:42:38 +00003564TEST(EachOf, TriggersForEachMatch) {
3565 EXPECT_TRUE(matchAndVerifyResultTrue(
3566 "class A { int a; int b; };",
3567 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3568 has(fieldDecl(hasName("b")).bind("v")))),
3569 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3570}
3571
3572TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3573 EXPECT_TRUE(matchAndVerifyResultTrue(
3574 "class A { int a; int c; };",
3575 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3576 has(fieldDecl(hasName("b")).bind("v")))),
3577 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3578 EXPECT_TRUE(matchAndVerifyResultTrue(
3579 "class A { int c; int b; };",
3580 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3581 has(fieldDecl(hasName("b")).bind("v")))),
3582 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3583 EXPECT_TRUE(notMatches(
3584 "class A { int c; int d; };",
3585 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3586 has(fieldDecl(hasName("b")).bind("v"))))));
3587}
Manuel Klimek04616e42012-07-06 05:48:52 +00003588
3589TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3590 // Make sure that we can both match the class by name (::X) and by the type
3591 // the template was instantiated with (via a field).
3592
3593 EXPECT_TRUE(matches(
3594 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003595 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003596
3597 EXPECT_TRUE(matches(
3598 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003599 recordDecl(isTemplateInstantiation(), hasDescendant(
3600 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003601}
3602
3603TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3604 EXPECT_TRUE(matches(
3605 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003606 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003607 isTemplateInstantiation())));
3608}
3609
3610TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3611 EXPECT_TRUE(matches(
3612 "template <typename T> class X { T t; }; class A {};"
3613 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003614 recordDecl(isTemplateInstantiation(), hasDescendant(
3615 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003616}
3617
3618TEST(IsTemplateInstantiation,
3619 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3620 EXPECT_TRUE(matches(
3621 "template <typename T> class X {};"
3622 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003623 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003624}
3625
3626TEST(IsTemplateInstantiation,
3627 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3628 EXPECT_TRUE(matches(
3629 "class A {};"
3630 "class X {"
3631 " template <typename U> class Y { U u; };"
3632 " Y<A> y;"
3633 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003634 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003635}
3636
3637TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3638 // FIXME: Figure out whether this makes sense. It doesn't affect the
3639 // normal use case as long as the uppermost instantiation always is marked
3640 // as template instantiation, but it might be confusing as a predicate.
3641 EXPECT_TRUE(matches(
3642 "class A {};"
3643 "template <typename T> class X {"
3644 " template <typename U> class Y { U u; };"
3645 " Y<T> y;"
3646 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003647 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003648}
3649
3650TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3651 EXPECT_TRUE(notMatches(
3652 "template <typename T> class X {}; class A {};"
3653 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003654 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003655}
3656
3657TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3658 EXPECT_TRUE(notMatches(
3659 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003660 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003661}
3662
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003663TEST(IsInstantiated, MatchesInstantiation) {
3664 EXPECT_TRUE(
3665 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3666 recordDecl(isInstantiated())));
3667}
3668
3669TEST(IsInstantiated, NotMatchesDefinition) {
3670 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3671 recordDecl(isInstantiated())));
3672}
3673
3674TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3675 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3676 "class Y { A<int> a; }; Y y;",
3677 declStmt(isInTemplateInstantiation())));
3678}
3679
3680TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3681 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3682 declStmt(isInTemplateInstantiation())));
3683}
3684
3685TEST(IsInstantiated, MatchesFunctionInstantiation) {
3686 EXPECT_TRUE(
3687 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3688 functionDecl(isInstantiated())));
3689}
3690
3691TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3692 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3693 varDecl(isInstantiated())));
3694}
3695
3696TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3697 EXPECT_TRUE(
3698 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3699 declStmt(isInTemplateInstantiation())));
3700}
3701
3702TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3703 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3704 declStmt(isInTemplateInstantiation())));
3705}
3706
3707TEST(IsInTemplateInstantiation, Sharing) {
3708 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3709 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3710 // and makes the matcher behave in non-obvious ways.
3711 EXPECT_TRUE(notMatches(
3712 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3713 Matcher));
3714 EXPECT_TRUE(matches(
3715 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3716 Matcher));
3717}
3718
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003719TEST(IsExplicitTemplateSpecialization,
3720 DoesNotMatchPrimaryTemplate) {
3721 EXPECT_TRUE(notMatches(
3722 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003723 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003724 EXPECT_TRUE(notMatches(
3725 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003726 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003727}
3728
3729TEST(IsExplicitTemplateSpecialization,
3730 DoesNotMatchExplicitTemplateInstantiations) {
3731 EXPECT_TRUE(notMatches(
3732 "template <typename T> class X {};"
3733 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003734 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003735 EXPECT_TRUE(notMatches(
3736 "template <typename T> void f(T t) {}"
3737 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003738 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003739}
3740
3741TEST(IsExplicitTemplateSpecialization,
3742 DoesNotMatchImplicitTemplateInstantiations) {
3743 EXPECT_TRUE(notMatches(
3744 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003745 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003746 EXPECT_TRUE(notMatches(
3747 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003748 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003749}
3750
3751TEST(IsExplicitTemplateSpecialization,
3752 MatchesExplicitTemplateSpecializations) {
3753 EXPECT_TRUE(matches(
3754 "template <typename T> class X {};"
3755 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003756 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003757 EXPECT_TRUE(matches(
3758 "template <typename T> void f(T t) {}"
3759 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003760 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003761}
3762
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003763TEST(HasAncenstor, MatchesDeclarationAncestors) {
3764 EXPECT_TRUE(matches(
3765 "class A { class B { class C {}; }; };",
3766 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3767}
3768
3769TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3770 EXPECT_TRUE(notMatches(
3771 "class A { class B { class C {}; }; };",
3772 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3773}
3774
3775TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3776 EXPECT_TRUE(matches(
3777 "class A { class B { void f() { C c; } class C {}; }; };",
3778 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3779 hasAncestor(recordDecl(hasName("A"))))))));
3780}
3781
3782TEST(HasAncenstor, MatchesStatementAncestors) {
3783 EXPECT_TRUE(matches(
3784 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003785 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003786}
3787
3788TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3789 EXPECT_TRUE(matches(
3790 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003791 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003792}
3793
3794TEST(HasAncestor, BindsRecursiveCombinations) {
3795 EXPECT_TRUE(matchAndVerifyResultTrue(
3796 "class C { class D { class E { class F { int y; }; }; }; };",
3797 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003798 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003799}
3800
3801TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3802 EXPECT_TRUE(matchAndVerifyResultTrue(
3803 "class C { class D { class E { class F { int y; }; }; }; };",
3804 fieldDecl(hasAncestor(
3805 decl(
3806 hasDescendant(recordDecl(isDefinition(),
3807 hasAncestor(recordDecl())))
3808 ).bind("d")
3809 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003810 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003811}
3812
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003813TEST(HasAncestor, MatchesClosestAncestor) {
3814 EXPECT_TRUE(matchAndVerifyResultTrue(
3815 "template <typename T> struct C {"
3816 " void f(int) {"
3817 " struct I { void g(T) { int x; } } i; i.g(42);"
3818 " }"
3819 "};"
3820 "template struct C<int>;",
3821 varDecl(hasName("x"),
3822 hasAncestor(functionDecl(hasParameter(
3823 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3824 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3825}
3826
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003827TEST(HasAncestor, MatchesInTemplateInstantiations) {
3828 EXPECT_TRUE(matches(
3829 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3830 "A<int>::B::C a;",
3831 fieldDecl(hasType(asString("int")),
3832 hasAncestor(recordDecl(hasName("A"))))));
3833}
3834
3835TEST(HasAncestor, MatchesInImplicitCode) {
3836 EXPECT_TRUE(matches(
3837 "struct X {}; struct A { A() {} X x; };",
3838 constructorDecl(
3839 hasAnyConstructorInitializer(withInitializer(expr(
3840 hasAncestor(recordDecl(hasName("A")))))))));
3841}
3842
Daniel Jasper632aea92012-10-22 16:26:51 +00003843TEST(HasParent, MatchesOnlyParent) {
3844 EXPECT_TRUE(matches(
3845 "void f() { if (true) { int x = 42; } }",
3846 compoundStmt(hasParent(ifStmt()))));
3847 EXPECT_TRUE(notMatches(
3848 "void f() { for (;;) { int x = 42; } }",
3849 compoundStmt(hasParent(ifStmt()))));
3850 EXPECT_TRUE(notMatches(
3851 "void f() { if (true) for (;;) { int x = 42; } }",
3852 compoundStmt(hasParent(ifStmt()))));
3853}
3854
Manuel Klimekc844a462012-12-06 14:42:48 +00003855TEST(HasAncestor, MatchesAllAncestors) {
3856 EXPECT_TRUE(matches(
3857 "template <typename T> struct C { static void f() { 42; } };"
3858 "void t() { C<int>::f(); }",
3859 integerLiteral(
3860 equals(42),
3861 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3862 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3863}
3864
3865TEST(HasParent, MatchesAllParents) {
3866 EXPECT_TRUE(matches(
3867 "template <typename T> struct C { static void f() { 42; } };"
3868 "void t() { C<int>::f(); }",
3869 integerLiteral(
3870 equals(42),
3871 hasParent(compoundStmt(hasParent(functionDecl(
3872 hasParent(recordDecl(isTemplateInstantiation())))))))));
3873 EXPECT_TRUE(matches(
3874 "template <typename T> struct C { static void f() { 42; } };"
3875 "void t() { C<int>::f(); }",
3876 integerLiteral(
3877 equals(42),
3878 hasParent(compoundStmt(hasParent(functionDecl(
3879 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3880 EXPECT_TRUE(matches(
3881 "template <typename T> struct C { static void f() { 42; } };"
3882 "void t() { C<int>::f(); }",
3883 integerLiteral(equals(42),
3884 hasParent(compoundStmt(allOf(
3885 hasParent(functionDecl(
3886 hasParent(recordDecl(isTemplateInstantiation())))),
3887 hasParent(functionDecl(hasParent(recordDecl(
3888 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003889 EXPECT_TRUE(
3890 notMatches("template <typename T> struct C { static void f() {} };"
3891 "void t() { C<int>::f(); }",
3892 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003893}
3894
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003895TEST(HasParent, NoDuplicateParents) {
3896 class HasDuplicateParents : public BoundNodesCallback {
3897 public:
3898 bool run(const BoundNodes *Nodes) override { return false; }
3899 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3900 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3901 std::set<const void *> Parents;
3902 for (const auto &Parent : Context->getParents(*Node)) {
3903 if (!Parents.insert(Parent.getMemoizationData()).second) {
3904 return true;
3905 }
3906 }
3907 return false;
3908 }
3909 };
3910 EXPECT_FALSE(matchAndVerifyResultTrue(
3911 "template <typename T> int Foo() { return 1 + 2; }\n"
3912 "int x = Foo<int>() + Foo<unsigned>();",
3913 stmt().bind("node"), new HasDuplicateParents()));
3914}
3915
Daniel Jasper516b02e2012-10-17 08:52:59 +00003916TEST(TypeMatching, MatchesTypes) {
3917 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3918}
3919
Samuel Benzaquenb405c082014-12-15 15:09:22 +00003920TEST(TypeMatching, MatchesVoid) {
3921 EXPECT_TRUE(
3922 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
3923}
3924
Daniel Jasper516b02e2012-10-17 08:52:59 +00003925TEST(TypeMatching, MatchesArrayTypes) {
3926 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3927 EXPECT_TRUE(matches("int a[42];", arrayType()));
3928 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3929
3930 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3931 arrayType(hasElementType(builtinType()))));
3932
3933 EXPECT_TRUE(matches(
3934 "int const a[] = { 2, 3 };",
3935 qualType(arrayType(hasElementType(builtinType())))));
3936 EXPECT_TRUE(matches(
3937 "int const a[] = { 2, 3 };",
3938 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3939 EXPECT_TRUE(matches(
3940 "typedef const int T; T x[] = { 1, 2 };",
3941 qualType(isConstQualified(), arrayType())));
3942
3943 EXPECT_TRUE(notMatches(
3944 "int a[] = { 2, 3 };",
3945 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3946 EXPECT_TRUE(notMatches(
3947 "int a[] = { 2, 3 };",
3948 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3949 EXPECT_TRUE(notMatches(
3950 "int const a[] = { 2, 3 };",
3951 qualType(arrayType(hasElementType(builtinType())),
3952 unless(isConstQualified()))));
3953
3954 EXPECT_TRUE(matches("int a[2];",
3955 constantArrayType(hasElementType(builtinType()))));
3956 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3957}
3958
3959TEST(TypeMatching, MatchesComplexTypes) {
3960 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3961 EXPECT_TRUE(matches(
3962 "_Complex float f;",
3963 complexType(hasElementType(builtinType()))));
3964 EXPECT_TRUE(notMatches(
3965 "_Complex float f;",
3966 complexType(hasElementType(isInteger()))));
3967}
3968
3969TEST(TypeMatching, MatchesConstantArrayTypes) {
3970 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3971 EXPECT_TRUE(notMatches(
3972 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3973 constantArrayType(hasElementType(builtinType()))));
3974
3975 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3976 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3977 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3978}
3979
3980TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3981 EXPECT_TRUE(matches(
3982 "template <typename T, int Size> class array { T data[Size]; };",
3983 dependentSizedArrayType()));
3984 EXPECT_TRUE(notMatches(
3985 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3986 dependentSizedArrayType()));
3987}
3988
3989TEST(TypeMatching, MatchesIncompleteArrayType) {
3990 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3991 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3992
3993 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3994 incompleteArrayType()));
3995}
3996
3997TEST(TypeMatching, MatchesVariableArrayType) {
3998 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3999 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4000
4001 EXPECT_TRUE(matches(
4002 "void f(int b) { int a[b]; }",
4003 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4004 varDecl(hasName("b")))))))));
4005}
4006
4007TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00004008 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4009 llvm::Triple::Win32) {
4010 // FIXME: Make this work for MSVC.
4011 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004012
David Majnemer197e2102014-03-05 06:32:38 +00004013 EXPECT_TRUE(matches("_Atomic(int) i;",
4014 atomicType(hasValueType(isInteger()))));
4015 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4016 atomicType(hasValueType(isInteger()))));
4017 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004018}
4019
4020TEST(TypeMatching, MatchesAutoTypes) {
4021 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4022 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4023 autoType()));
4024
Richard Smith061f1e22013-04-30 21:23:01 +00004025 // FIXME: Matching against the type-as-written can't work here, because the
4026 // type as written was not deduced.
4027 //EXPECT_TRUE(matches("auto a = 1;",
4028 // autoType(hasDeducedType(isInteger()))));
4029 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4030 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004031}
4032
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004033TEST(TypeMatching, MatchesFunctionTypes) {
4034 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4035 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4036}
4037
Edwin Vaneec074802013-04-01 18:33:34 +00004038TEST(TypeMatching, MatchesParenType) {
4039 EXPECT_TRUE(
4040 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4041 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4042
4043 EXPECT_TRUE(matches(
4044 "int (*ptr_to_func)(int);",
4045 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4046 EXPECT_TRUE(notMatches(
4047 "int (*ptr_to_array)[4];",
4048 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4049}
4050
Daniel Jasper516b02e2012-10-17 08:52:59 +00004051TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004052 // FIXME: Reactive when these tests can be more specific (not matching
4053 // implicit code on certain platforms), likely when we have hasDescendant for
4054 // Types/TypeLocs.
4055 //EXPECT_TRUE(matchAndVerifyResultTrue(
4056 // "int* a;",
4057 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4058 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4059 //EXPECT_TRUE(matchAndVerifyResultTrue(
4060 // "int* a;",
4061 // pointerTypeLoc().bind("loc"),
4062 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004063 EXPECT_TRUE(matches(
4064 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004065 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004066 EXPECT_TRUE(matches(
4067 "int** a;",
4068 loc(pointerType(pointee(pointerType())))));
4069 EXPECT_TRUE(matches(
4070 "int* b; int* * const a = &b;",
4071 loc(qualType(isConstQualified(), pointerType()))));
4072
4073 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004074 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4075 hasType(blockPointerType()))));
4076 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4077 hasType(memberPointerType()))));
4078 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4079 hasType(pointerType()))));
4080 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4081 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004082 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4083 hasType(lValueReferenceType()))));
4084 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4085 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004086
Daniel Jasper7943eb52012-10-17 13:35:36 +00004087 Fragment = "int *ptr;";
4088 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4089 hasType(blockPointerType()))));
4090 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4091 hasType(memberPointerType()))));
4092 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4093 hasType(pointerType()))));
4094 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4095 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004096
Daniel Jasper7943eb52012-10-17 13:35:36 +00004097 Fragment = "int a; int &ref = a;";
4098 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4099 hasType(blockPointerType()))));
4100 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4101 hasType(memberPointerType()))));
4102 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4103 hasType(pointerType()))));
4104 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4105 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004106 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4107 hasType(lValueReferenceType()))));
4108 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4109 hasType(rValueReferenceType()))));
4110
4111 Fragment = "int &&ref = 2;";
4112 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4113 hasType(blockPointerType()))));
4114 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4115 hasType(memberPointerType()))));
4116 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4117 hasType(pointerType()))));
4118 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4119 hasType(referenceType()))));
4120 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4121 hasType(lValueReferenceType()))));
4122 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4123 hasType(rValueReferenceType()))));
4124}
4125
4126TEST(TypeMatching, AutoRefTypes) {
4127 std::string Fragment = "auto a = 1;"
4128 "auto b = a;"
4129 "auto &c = a;"
4130 "auto &&d = c;"
4131 "auto &&e = 2;";
4132 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4133 hasType(referenceType()))));
4134 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4135 hasType(referenceType()))));
4136 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4137 hasType(referenceType()))));
4138 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4139 hasType(lValueReferenceType()))));
4140 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4141 hasType(rValueReferenceType()))));
4142 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4143 hasType(referenceType()))));
4144 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4145 hasType(lValueReferenceType()))));
4146 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4147 hasType(rValueReferenceType()))));
4148 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4149 hasType(referenceType()))));
4150 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4151 hasType(lValueReferenceType()))));
4152 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4153 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004154}
4155
4156TEST(TypeMatching, PointeeTypes) {
4157 EXPECT_TRUE(matches("int b; int &a = b;",
4158 referenceType(pointee(builtinType()))));
4159 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4160
4161 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004162 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004163
4164 EXPECT_TRUE(matches(
4165 "int const *A;",
4166 pointerType(pointee(isConstQualified(), builtinType()))));
4167 EXPECT_TRUE(notMatches(
4168 "int *A;",
4169 pointerType(pointee(isConstQualified(), builtinType()))));
4170}
4171
4172TEST(TypeMatching, MatchesPointersToConstTypes) {
4173 EXPECT_TRUE(matches("int b; int * const a = &b;",
4174 loc(pointerType())));
4175 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004176 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004177 EXPECT_TRUE(matches(
4178 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004179 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004180 EXPECT_TRUE(matches(
4181 "int b; const int * a = &b;",
4182 pointerType(pointee(builtinType()))));
4183}
4184
4185TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004186 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4187 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004188}
4189
Edwin Vanef901b712013-02-25 14:49:29 +00004190TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004191 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004192 templateSpecializationType()));
4193}
4194
Edwin Vaneb6eae142013-02-25 20:43:32 +00004195TEST(TypeMatching, MatchesRecordType) {
4196 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004197 EXPECT_TRUE(matches("struct S{}; S s;",
4198 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4199 EXPECT_TRUE(notMatches("int i;",
4200 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004201}
4202
4203TEST(TypeMatching, MatchesElaboratedType) {
4204 EXPECT_TRUE(matches(
4205 "namespace N {"
4206 " namespace M {"
4207 " class D {};"
4208 " }"
4209 "}"
4210 "N::M::D d;", elaboratedType()));
4211 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4212 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4213}
4214
4215TEST(ElaboratedTypeNarrowing, hasQualifier) {
4216 EXPECT_TRUE(matches(
4217 "namespace N {"
4218 " namespace M {"
4219 " class D {};"
4220 " }"
4221 "}"
4222 "N::M::D d;",
4223 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4224 EXPECT_TRUE(notMatches(
4225 "namespace M {"
4226 " class D {};"
4227 "}"
4228 "M::D d;",
4229 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004230 EXPECT_TRUE(notMatches(
4231 "struct D {"
4232 "} d;",
4233 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004234}
4235
4236TEST(ElaboratedTypeNarrowing, namesType) {
4237 EXPECT_TRUE(matches(
4238 "namespace N {"
4239 " namespace M {"
4240 " class D {};"
4241 " }"
4242 "}"
4243 "N::M::D d;",
4244 elaboratedType(elaboratedType(namesType(recordType(
4245 hasDeclaration(namedDecl(hasName("D")))))))));
4246 EXPECT_TRUE(notMatches(
4247 "namespace M {"
4248 " class D {};"
4249 "}"
4250 "M::D d;",
4251 elaboratedType(elaboratedType(namesType(typedefType())))));
4252}
4253
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004254TEST(NNS, MatchesNestedNameSpecifiers) {
4255 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4256 nestedNameSpecifier()));
4257 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4258 nestedNameSpecifier()));
4259 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4260 nestedNameSpecifier()));
4261
4262 EXPECT_TRUE(matches(
4263 "struct A { static void f() {} }; void g() { A::f(); }",
4264 nestedNameSpecifier()));
4265 EXPECT_TRUE(notMatches(
4266 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4267 nestedNameSpecifier()));
4268}
4269
Daniel Jasper87c3d362012-09-20 14:12:57 +00004270TEST(NullStatement, SimpleCases) {
4271 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4272 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4273}
4274
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004275TEST(NNS, MatchesTypes) {
4276 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4277 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4278 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4279 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4280 Matcher));
4281 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4282}
4283
4284TEST(NNS, MatchesNamespaceDecls) {
4285 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4286 specifiesNamespace(hasName("ns")));
4287 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4288 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4289 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4290}
4291
4292TEST(NNS, BindsNestedNameSpecifiers) {
4293 EXPECT_TRUE(matchAndVerifyResultTrue(
4294 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4295 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4296 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4297}
4298
4299TEST(NNS, BindsNestedNameSpecifierLocs) {
4300 EXPECT_TRUE(matchAndVerifyResultTrue(
4301 "namespace ns { struct B {}; } ns::B b;",
4302 loc(nestedNameSpecifier()).bind("loc"),
4303 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4304}
4305
4306TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4307 EXPECT_TRUE(matches(
4308 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4309 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4310 EXPECT_TRUE(matches(
4311 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004312 nestedNameSpecifierLoc(hasPrefix(
4313 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004314}
4315
Daniel Jasper6fc34332012-10-30 15:42:00 +00004316TEST(NNS, DescendantsOfNestedNameSpecifiers) {
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 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4323 hasDescendant(nestedNameSpecifier(
4324 specifiesNamespace(hasName("a")))))));
4325 EXPECT_TRUE(notMatches(
4326 Fragment,
4327 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4328 has(nestedNameSpecifier(
4329 specifiesNamespace(hasName("a")))))));
4330 EXPECT_TRUE(matches(
4331 Fragment,
4332 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4333 has(nestedNameSpecifier(
4334 specifiesNamespace(hasName("a")))))));
4335
4336 // Not really useful because a NestedNameSpecifier can af at most one child,
4337 // but to complete the interface.
4338 EXPECT_TRUE(matchAndVerifyResultTrue(
4339 Fragment,
4340 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4341 forEach(nestedNameSpecifier().bind("x"))),
4342 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4343}
4344
4345TEST(NNS, NestedNameSpecifiersAsDescendants) {
4346 std::string Fragment =
4347 "namespace a { struct A { struct B { struct C {}; }; }; };"
4348 "void f() { a::A::B::C c; }";
4349 EXPECT_TRUE(matches(
4350 Fragment,
4351 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4352 asString("struct a::A")))))));
4353 EXPECT_TRUE(matchAndVerifyResultTrue(
4354 Fragment,
4355 functionDecl(hasName("f"),
4356 forEachDescendant(nestedNameSpecifier().bind("x"))),
4357 // Nested names: a, a::A and a::A::B.
4358 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4359}
4360
4361TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4362 std::string Fragment =
4363 "namespace a { struct A { struct B { struct C {}; }; }; };"
4364 "void f() { a::A::B::C c; }";
4365 EXPECT_TRUE(matches(
4366 Fragment,
4367 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4368 hasDescendant(loc(nestedNameSpecifier(
4369 specifiesNamespace(hasName("a"))))))));
4370 EXPECT_TRUE(notMatches(
4371 Fragment,
4372 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4373 has(loc(nestedNameSpecifier(
4374 specifiesNamespace(hasName("a"))))))));
4375 EXPECT_TRUE(matches(
4376 Fragment,
4377 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4378 has(loc(nestedNameSpecifier(
4379 specifiesNamespace(hasName("a"))))))));
4380
4381 EXPECT_TRUE(matchAndVerifyResultTrue(
4382 Fragment,
4383 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4384 forEach(nestedNameSpecifierLoc().bind("x"))),
4385 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4386}
4387
4388TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4389 std::string Fragment =
4390 "namespace a { struct A { struct B { struct C {}; }; }; };"
4391 "void f() { a::A::B::C c; }";
4392 EXPECT_TRUE(matches(
4393 Fragment,
4394 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4395 asString("struct a::A"))))))));
4396 EXPECT_TRUE(matchAndVerifyResultTrue(
4397 Fragment,
4398 functionDecl(hasName("f"),
4399 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4400 // Nested names: a, a::A and a::A::B.
4401 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4402}
4403
Manuel Klimek191c0932013-02-01 13:41:35 +00004404template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004405public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004406 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4407 StringRef InnerId)
4408 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004409 }
4410
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004411 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004412
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004413 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004414 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004415 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4416 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004417 }
4418private:
4419 std::string Id;
4420 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004421 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004422};
4423
4424TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004425 EXPECT_TRUE(matchAndVerifyResultTrue(
4426 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4427 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004428 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4429 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004430 EXPECT_TRUE(matchAndVerifyResultFalse(
4431 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4432 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004433 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4434 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004435}
4436
4437TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004438 EXPECT_TRUE(matchAndVerifyResultTrue(
4439 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004440 new VerifyMatchOnNode<clang::Stmt>(
4441 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004442 EXPECT_TRUE(matchAndVerifyResultFalse(
4443 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004444 new VerifyMatchOnNode<clang::Stmt>(
4445 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004446}
4447
4448TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4449 EXPECT_TRUE(matchAndVerifyResultTrue(
4450 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4451 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004452 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004453 EXPECT_TRUE(matchAndVerifyResultFalse(
4454 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4455 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004456 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004457}
4458
Manuel Klimekbee08572013-02-07 12:42:10 +00004459template <typename T>
4460class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4461public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004462 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004463
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004464 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004465 const T *Node = Nodes->getNodeAs<T>("");
4466 return verify(*Nodes, *Context, Node);
4467 }
4468
4469 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004470 // Use the original typed pointer to verify we can pass pointers to subtypes
4471 // to equalsNode.
4472 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004473 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004474 "", match(stmt(hasParent(
4475 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004476 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004477 }
4478 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004479 // Use the original typed pointer to verify we can pass pointers to subtypes
4480 // to equalsNode.
4481 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004482 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004483 "", match(decl(hasParent(
4484 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004485 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004486 }
4487};
4488
4489TEST(IsEqualTo, MatchesNodesByIdentity) {
4490 EXPECT_TRUE(matchAndVerifyResultTrue(
4491 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004492 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4493 EXPECT_TRUE(matchAndVerifyResultTrue(
4494 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4495 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004496}
4497
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004498TEST(MatchFinder, CheckProfiling) {
4499 MatchFinder::MatchFinderOptions Options;
4500 llvm::StringMap<llvm::TimeRecord> Records;
4501 Options.CheckProfiling.emplace(Records);
4502 MatchFinder Finder(std::move(Options));
4503
4504 struct NamedCallback : public MatchFinder::MatchCallback {
4505 void run(const MatchFinder::MatchResult &Result) override {}
4506 StringRef getID() const override { return "MyID"; }
4507 } Callback;
4508 Finder.addMatcher(decl(), &Callback);
4509 std::unique_ptr<FrontendActionFactory> Factory(
4510 newFrontendActionFactory(&Finder));
4511 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4512
4513 EXPECT_EQ(1u, Records.size());
4514 EXPECT_EQ("MyID", Records.begin()->getKey());
4515}
4516
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004517class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4518public:
4519 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004520 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004521 EXPECT_TRUE(Called);
4522 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004523 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004524 bool Called;
4525};
4526
4527TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4528 MatchFinder Finder;
4529 VerifyStartOfTranslationUnit VerifyCallback;
4530 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004531 std::unique_ptr<FrontendActionFactory> Factory(
4532 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004533 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4534 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004535
4536 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004537 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004538 ASSERT_TRUE(AST.get());
4539 Finder.matchAST(AST->getASTContext());
4540 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004541}
4542
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004543class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4544public:
4545 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004546 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004547 EXPECT_FALSE(Called);
4548 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004549 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004550 bool Called;
4551};
4552
4553TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4554 MatchFinder Finder;
4555 VerifyEndOfTranslationUnit VerifyCallback;
4556 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004557 std::unique_ptr<FrontendActionFactory> Factory(
4558 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004559 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4560 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004561
4562 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004563 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004564 ASSERT_TRUE(AST.get());
4565 Finder.matchAST(AST->getASTContext());
4566 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004567}
4568
Manuel Klimekbbb75852013-06-20 14:06:32 +00004569TEST(EqualsBoundNodeMatcher, QualType) {
4570 EXPECT_TRUE(matches(
4571 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4572 hasInitializer(ignoringParenImpCasts(
4573 hasType(qualType(equalsBoundNode("type"))))))));
4574 EXPECT_TRUE(notMatches("int i = 1.f;",
4575 varDecl(hasType(qualType().bind("type")),
4576 hasInitializer(ignoringParenImpCasts(hasType(
4577 qualType(equalsBoundNode("type"))))))));
4578}
4579
4580TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4581 EXPECT_TRUE(notMatches(
4582 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4583 hasInitializer(ignoringParenImpCasts(
4584 hasType(qualType(equalsBoundNode("type"))))))));
4585}
4586
4587TEST(EqualsBoundNodeMatcher, Stmt) {
4588 EXPECT_TRUE(
4589 matches("void f() { if(true) {} }",
4590 stmt(allOf(ifStmt().bind("if"),
4591 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4592
4593 EXPECT_TRUE(notMatches(
4594 "void f() { if(true) { if (true) {} } }",
4595 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4596}
4597
4598TEST(EqualsBoundNodeMatcher, Decl) {
4599 EXPECT_TRUE(matches(
4600 "class X { class Y {}; };",
4601 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4602 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4603
4604 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4605 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4606 has(decl(equalsBoundNode("record")))))));
4607}
4608
4609TEST(EqualsBoundNodeMatcher, Type) {
4610 EXPECT_TRUE(matches(
4611 "class X { int a; int b; };",
4612 recordDecl(
4613 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4614 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4615
4616 EXPECT_TRUE(notMatches(
4617 "class X { int a; double b; };",
4618 recordDecl(
4619 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4620 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4621}
4622
4623TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004624 EXPECT_TRUE(matchAndVerifyResultTrue(
4625 "int f() {"
4626 " if (1) {"
4627 " int i = 9;"
4628 " }"
4629 " int j = 10;"
4630 " {"
4631 " float k = 9.0;"
4632 " }"
4633 " return 0;"
4634 "}",
4635 // Look for variable declarations within functions whose type is the same
4636 // as the function return type.
4637 functionDecl(returns(qualType().bind("type")),
4638 forEachDescendant(varDecl(hasType(
4639 qualType(equalsBoundNode("type")))).bind("decl"))),
4640 // Only i and j should match, not k.
4641 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4642}
4643
4644TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4645 EXPECT_TRUE(matchAndVerifyResultTrue(
4646 "void f() {"
4647 " int x;"
4648 " double d;"
4649 " x = d + x - d + x;"
4650 "}",
4651 functionDecl(
4652 hasName("f"), forEachDescendant(varDecl().bind("d")),
4653 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4654 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4655}
4656
Manuel Klimekce68f772014-03-25 14:39:26 +00004657TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4658 EXPECT_TRUE(matchAndVerifyResultTrue(
4659 "struct StringRef { int size() const; const char* data() const; };"
4660 "void f(StringRef v) {"
4661 " v.data();"
4662 "}",
4663 memberCallExpr(
4664 callee(methodDecl(hasName("data"))),
4665 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4666 .bind("var")))),
4667 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4668 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4669 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4670 .bind("data"),
4671 new VerifyIdIsBoundTo<Expr>("data", 1)));
4672
4673 EXPECT_FALSE(matches(
4674 "struct StringRef { int size() const; const char* data() const; };"
4675 "void f(StringRef v) {"
4676 " v.data();"
4677 " v.size();"
4678 "}",
4679 memberCallExpr(
4680 callee(methodDecl(hasName("data"))),
4681 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4682 .bind("var")))),
4683 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4684 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4685 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4686 .bind("data")));
4687}
4688
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004689TEST(TypeDefDeclMatcher, Match) {
4690 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4691 typedefDecl(hasName("typedefDeclTest"))));
4692}
4693
4694// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4695#ifndef LLVM_ON_WIN32
4696
4697TEST(Matcher, IsExpansionInMainFileMatcher) {
4698 EXPECT_TRUE(matches("class X {};",
4699 recordDecl(hasName("X"), isExpansionInMainFile())));
4700 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4701 FileContentMappings M;
4702 M.push_back(std::make_pair("/other", "class X {};"));
4703 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4704 recordDecl(isExpansionInMainFile()), false,
4705 "-isystem/", M));
4706}
4707
4708TEST(Matcher, IsExpansionInSystemHeader) {
4709 FileContentMappings M;
4710 M.push_back(std::make_pair("/other", "class X {};"));
4711 EXPECT_TRUE(matchesConditionally(
4712 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4713 "-isystem/", M));
4714 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4715 recordDecl(isExpansionInSystemHeader()),
4716 false, "-I/", M));
4717 EXPECT_TRUE(notMatches("class X {};",
4718 recordDecl(isExpansionInSystemHeader())));
4719 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4720}
4721
4722TEST(Matcher, IsExpansionInFileMatching) {
4723 FileContentMappings M;
4724 M.push_back(std::make_pair("/foo", "class A {};"));
4725 M.push_back(std::make_pair("/bar", "class B {};"));
4726 EXPECT_TRUE(matchesConditionally(
4727 "#include <foo>\n"
4728 "#include <bar>\n"
4729 "class X {};",
4730 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4731 "-isystem/", M));
4732 EXPECT_TRUE(matchesConditionally(
4733 "#include <foo>\n"
4734 "#include <bar>\n"
4735 "class X {};",
4736 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4737 "-isystem/", M));
4738}
4739
4740#endif // LLVM_ON_WIN32
4741
Manuel Klimekbfa43572015-03-12 15:48:15 +00004742
4743TEST(ObjCMessageExprMatcher, SimpleExprs) {
4744 // don't find ObjCMessageExpr where none are present
4745 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
4746
4747 std::string Objc1String =
4748 "@interface Str "
4749 " - (Str *)uppercaseString:(Str *)str;"
4750 "@end "
4751 "@interface foo "
4752 "- (void)meth:(Str *)text;"
4753 "@end "
4754 " "
4755 "@implementation foo "
4756 "- (void) meth:(Str *)text { "
4757 " [self contents];"
4758 " Str *up = [text uppercaseString];"
4759 "} "
4760 "@end ";
4761 EXPECT_TRUE(matchesObjC(
4762 Objc1String,
4763 objcMessageExpr(anything())));
4764 EXPECT_TRUE(matchesObjC(
4765 Objc1String,
4766 objcMessageExpr(hasSelector("contents"))));
4767 EXPECT_TRUE(matchesObjC(
4768 Objc1String,
4769 objcMessageExpr(matchesSelector("cont*"))));
4770 EXPECT_FALSE(matchesObjC(
4771 Objc1String,
4772 objcMessageExpr(matchesSelector("?cont*"))));
4773 EXPECT_TRUE(notMatchesObjC(
4774 Objc1String,
4775 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
4776 EXPECT_TRUE(matchesObjC(
4777 Objc1String,
4778 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
4779 EXPECT_TRUE(matchesObjC(
4780 Objc1String,
4781 objcMessageExpr(matchesSelector("uppercase*"),
4782 argumentCountIs(0)
4783 )));
4784
4785}
4786
Manuel Klimek04616e42012-07-06 05:48:52 +00004787} // end namespace ast_matchers
4788} // end namespace clang