blob: 9aefb07809173b4abad9da4239853bf81185ab04 [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({
Aaron Ballman512fb642015-09-17 13:30:52 +000039 DeclarationMatcher IsDerivedFromEmpty = cxxRecordDecl(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) {
Aaron Ballman512fb642015-09-17 13:30:52 +0000125 DeclarationMatcher IsDerivedFromX = cxxRecordDecl(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
Aaron Ballman512fb642015-09-17 13:30:52 +0000133 DeclarationMatcher IsAX = cxxRecordDecl(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 =
Aaron Ballman512fb642015-09-17 13:30:52 +0000142 cxxRecordDecl(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> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000261 cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
Manuel Klimek5472a522012-12-04 13:40:29 +0000262 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> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000268 cxxRecordDecl(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"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000285 hasInitializer(hasType(cxxRecordDecl(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"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000289 hasInitializer(hasType(cxxRecordDecl(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"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000293 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000294 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"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000310 hasInitializer(hasType(cxxRecordDecl(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"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000314 hasInitializer(hasType(cxxRecordDecl(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"),
Aaron Ballman512fb642015-09-17 13:30:52 +0000318 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000319 isDerivedFrom("Base2")))))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Aaron Ballman512fb642015-09-17 13:30:52 +0000322 cxxRecordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000325 cxxRecordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000329 cxxRecordDecl(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> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +0000335 cxxRecordDecl(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(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +0000340 cxxRecordDecl(hasMethod(hasName("func")))));
Edwin Vane0a4836e2013-03-06 17:02:57 +0000341 EXPECT_TRUE(notMatches("class A { void func(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +0000342 cxxRecordDecl(hasMethod(isPublic()))));
Edwin Vane0a4836e2013-03-06 17:02:57 +0000343}
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;",
Aaron Ballman512fb642015-09-17 13:30:52 +0000352 cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
Daniel Jasper83dafaf2012-09-18 14:17:42 +0000353}
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
Samuel Benzaquenb063f5c2015-07-17 16:05:27 +0000456TEST(ConstructVariadic, MismatchedTypes_Regression) {
457 EXPECT_TRUE(
458 matches("const int a = 0;",
459 internal::DynTypedMatcher::constructVariadic(
460 internal::DynTypedMatcher::VO_AnyOf,
461 ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>(),
462 {isConstQualified(), arrayType()})
463 .convertTo<QualType>()));
464}
465
Manuel Klimek04616e42012-07-06 05:48:52 +0000466TEST(DeclarationMatcher, MatchAnyOf) {
Aaron Ballman512fb642015-09-17 13:30:52 +0000467 DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
468 anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
469 EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
Manuel Klimek04616e42012-07-06 05:48:52 +0000470 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
471 EXPECT_TRUE(
472 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
473 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
474
Daniel Jasper84c763e2012-07-15 19:57:12 +0000475 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000476 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000477 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
478 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
479
Manuel Klimek04616e42012-07-06 05:48:52 +0000480 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000481 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
482 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000483 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
484 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
485 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
486 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
487 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
488 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000489
490 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
491 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
492 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
493 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Aaron Ballman8f4699a2015-07-02 14:02:41 +0000494
495 EXPECT_TRUE(
496 matches("void f() try { } catch (int) { } catch (...) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +0000497 cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000498}
499
500TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000501 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000502 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
503 EXPECT_TRUE(matches("class X {};", HasClassX));
504
505 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000506 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000507 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
508 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
509 EXPECT_TRUE(
510 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
511}
512
513TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
514 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000515 recordDecl(
516 has(recordDecl(
517 has(recordDecl(hasName("X"))),
518 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000519 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000520 has(recordDecl(
521 has(recordDecl(hasName("A"))),
522 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000523 hasName("C"))),
524 hasName("F"));
525
526 EXPECT_TRUE(matches(
527 "class F {"
528 " class Z {"
529 " class X {};"
530 " class Y {};"
531 " };"
532 " class C {"
533 " class A {};"
534 " class B {};"
535 " };"
536 "};", Recursive));
537
538 EXPECT_TRUE(matches(
539 "class F {"
540 " class Z {"
541 " class A {};"
542 " class X {};"
543 " class Y {};"
544 " };"
545 " class C {"
546 " class X {};"
547 " class A {};"
548 " class B {};"
549 " };"
550 "};", Recursive));
551
552 EXPECT_TRUE(matches(
553 "class O1 {"
554 " class O2 {"
555 " class F {"
556 " class Z {"
557 " class A {};"
558 " class X {};"
559 " class Y {};"
560 " };"
561 " class C {"
562 " class X {};"
563 " class A {};"
564 " class B {};"
565 " };"
566 " };"
567 " };"
568 "};", Recursive));
569}
570
571TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
572 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000573 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000574 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000575 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000576 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000577 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000578 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000579 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000580 hasName("Y"))),
581 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000582 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000583 anyOf(
584 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000585 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000586 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000587 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000588 hasName("B")))))),
589 hasName("F")));
590
591 EXPECT_TRUE(matches("class F {};", Recursive));
592 EXPECT_TRUE(matches("class Z {};", Recursive));
593 EXPECT_TRUE(matches("class C {};", Recursive));
594 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
595 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
596 EXPECT_TRUE(
597 matches("class O1 { class O2 {"
598 " class M { class N { class B {}; }; }; "
599 "}; };", Recursive));
600}
601
602TEST(DeclarationMatcher, MatchNot) {
603 DeclarationMatcher NotClassX =
Aaron Ballman512fb642015-09-17 13:30:52 +0000604 cxxRecordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000605 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000606 unless(hasName("X")));
607 EXPECT_TRUE(notMatches("", NotClassX));
608 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
609 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
610 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
611 EXPECT_TRUE(
612 notMatches("class Y {}; class Z {}; class X : public Y {};",
613 NotClassX));
614
615 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000616 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000617 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000618 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000619 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000620 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000621 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
622 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
623 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000624
625 DeclarationMatcher NamedNotRecord =
626 namedDecl(hasName("Foo"), unless(recordDecl()));
627 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
628 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000629}
630
631TEST(DeclarationMatcher, HasDescendant) {
632 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000633 recordDecl(
634 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000635 hasName("Z"));
636 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
637 EXPECT_TRUE(
638 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
639 EXPECT_TRUE(
640 matches("class Z { class A { class Y { class X {}; }; }; };",
641 ZDescendantClassX));
642 EXPECT_TRUE(
643 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
644 ZDescendantClassX));
645 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
646
647 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000648 recordDecl(
649 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000650 hasName("X"))),
651 hasName("Z"));
652 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
653 ZDescendantClassXHasClassY));
654 EXPECT_TRUE(
655 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
656 ZDescendantClassXHasClassY));
657 EXPECT_TRUE(notMatches(
658 "class Z {"
659 " class A {"
660 " class B {"
661 " class X {"
662 " class C {"
663 " class Y {};"
664 " };"
665 " };"
666 " }; "
667 " };"
668 "};", ZDescendantClassXHasClassY));
669
670 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000671 recordDecl(
672 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
673 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000674 hasName("Z"));
675 EXPECT_TRUE(
676 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
677 ZDescendantClassXDescendantClassY));
678 EXPECT_TRUE(matches(
679 "class Z {"
680 " class A {"
681 " class X {"
682 " class B {"
683 " class Y {};"
684 " };"
685 " class Y {};"
686 " };"
687 " };"
688 "};", ZDescendantClassXDescendantClassY));
689}
690
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000691TEST(DeclarationMatcher, HasDescendantMemoization) {
692 DeclarationMatcher CannotMemoize =
693 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
694 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
695}
696
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000697TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
698 auto Name = hasName("i");
699 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
700 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
701 // Matching VD first should not make a cache hit for RD.
702 EXPECT_TRUE(notMatches("void f() { int i; }",
703 decl(hasDescendant(VD), hasDescendant(RD))));
704 EXPECT_TRUE(notMatches("void f() { int i; }",
705 decl(hasDescendant(RD), hasDescendant(VD))));
706 // Not matching RD first should not make a cache hit for VD either.
707 EXPECT_TRUE(matches("void f() { int i; }",
708 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
709}
710
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000711TEST(DeclarationMatcher, HasAttr) {
712 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
713 decl(hasAttr(clang::attr::WarnUnused))));
714 EXPECT_FALSE(matches("struct X {};",
715 decl(hasAttr(clang::attr::WarnUnused))));
716}
717
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000718TEST(DeclarationMatcher, MatchCudaDecl) {
719 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
720 "void g() { f<<<1, 2>>>(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +0000721 cudaKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000722 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000723 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000724 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Aaron Ballman512fb642015-09-17 13:30:52 +0000725 cudaKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000726 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000727 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000728}
729
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000730// Implements a run method that returns whether BoundNodes contains a
731// Decl bound to Id that can be dynamically cast to T.
732// Optionally checks that the check succeeded a specific number of times.
733template <typename T>
734class VerifyIdIsBoundTo : public BoundNodesCallback {
735public:
736 // Create an object that checks that a node of type \c T was bound to \c Id.
737 // Does not check for a certain number of matches.
738 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
739 : Id(Id), ExpectedCount(-1), Count(0) {}
740
741 // Create an object that checks that a node of type \c T was bound to \c Id.
742 // Checks that there were exactly \c ExpectedCount matches.
743 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
744 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
745
746 // Create an object that checks that a node of type \c T was bound to \c Id.
747 // Checks that there was exactly one match with the name \c ExpectedName.
748 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000749 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
750 int ExpectedCount = 1)
751 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
752 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000753
Craig Toppera798a9d2014-03-02 09:32:10 +0000754 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000755 if (ExpectedCount != -1)
756 EXPECT_EQ(ExpectedCount, Count);
757 if (!ExpectedName.empty())
758 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000759 Count = 0;
760 Name.clear();
761 }
762
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000763 ~VerifyIdIsBoundTo() override {
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000764 EXPECT_EQ(0, Count);
765 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000766 }
767
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000768 bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000769 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000770 if (Nodes->getNodeAs<T>(Id)) {
771 ++Count;
772 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
773 Name = Named->getNameAsString();
774 } else if (const NestedNameSpecifier *NNS =
775 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
776 llvm::raw_string_ostream OS(Name);
777 NNS->print(OS, PrintingPolicy(LangOptions()));
778 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000779 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
780 EXPECT_NE(M.end(), I);
781 if (I != M.end())
782 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000783 return true;
784 }
Craig Topper416fa342014-06-08 08:38:12 +0000785 EXPECT_TRUE(M.count(Id) == 0 ||
786 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000787 return false;
788 }
789
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000790 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000791 return run(Nodes);
792 }
793
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000794private:
795 const std::string Id;
796 const int ExpectedCount;
797 int Count;
798 const std::string ExpectedName;
799 std::string Name;
800};
801
802TEST(HasDescendant, MatchesDescendantTypes) {
803 EXPECT_TRUE(matches("void f() { int i = 3; }",
804 decl(hasDescendant(loc(builtinType())))));
805 EXPECT_TRUE(matches("void f() { int i = 3; }",
806 stmt(hasDescendant(builtinType()))));
807
808 EXPECT_TRUE(matches("void f() { int i = 3; }",
809 stmt(hasDescendant(loc(builtinType())))));
810 EXPECT_TRUE(matches("void f() { int i = 3; }",
811 stmt(hasDescendant(qualType(builtinType())))));
812
813 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
814 stmt(hasDescendant(isInteger()))));
815
816 EXPECT_TRUE(matchAndVerifyResultTrue(
817 "void f() { int a; float c; int d; int e; }",
818 functionDecl(forEachDescendant(
819 varDecl(hasDescendant(isInteger())).bind("x"))),
820 new VerifyIdIsBoundTo<Decl>("x", 3)));
821}
822
823TEST(HasDescendant, MatchesDescendantsOfTypes) {
824 EXPECT_TRUE(matches("void f() { int*** i; }",
825 qualType(hasDescendant(builtinType()))));
826 EXPECT_TRUE(matches("void f() { int*** i; }",
827 qualType(hasDescendant(
828 pointerType(pointee(builtinType()))))));
829 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000830 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000831
832 EXPECT_TRUE(matchAndVerifyResultTrue(
833 "void f() { int*** i; }",
834 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
835 new VerifyIdIsBoundTo<Type>("x", 2)));
836}
837
838TEST(Has, MatchesChildrenOfTypes) {
839 EXPECT_TRUE(matches("int i;",
840 varDecl(hasName("i"), has(isInteger()))));
841 EXPECT_TRUE(notMatches("int** i;",
842 varDecl(hasName("i"), has(isInteger()))));
843 EXPECT_TRUE(matchAndVerifyResultTrue(
844 "int (*f)(float, int);",
845 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
846 new VerifyIdIsBoundTo<QualType>("x", 2)));
847}
848
849TEST(Has, MatchesChildTypes) {
850 EXPECT_TRUE(matches(
851 "int* i;",
852 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
853 EXPECT_TRUE(notMatches(
854 "int* i;",
855 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
856}
857
Samuel Benzaquenc640ef52014-10-28 13:33:58 +0000858TEST(ValueDecl, Matches) {
859 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
860 valueDecl(hasType(asString("enum EnumType")))));
861 EXPECT_TRUE(matches("void FunctionDecl();",
862 valueDecl(hasType(asString("void (void)")))));
863}
864
Daniel Jasper1dad1832012-07-10 20:20:19 +0000865TEST(Enum, DoesNotMatchClasses) {
866 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
867}
868
869TEST(Enum, MatchesEnums) {
870 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
871}
872
873TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000874 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000875 EXPECT_TRUE(matches("enum X{ A };", Matcher));
876 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
877 EXPECT_TRUE(notMatches("enum X {};", Matcher));
878}
879
Manuel Klimek04616e42012-07-06 05:48:52 +0000880TEST(StatementMatcher, Has) {
881 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000882 expr(hasType(pointsTo(recordDecl(hasName("X")))),
883 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000884
885 EXPECT_TRUE(matches(
886 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
887 EXPECT_TRUE(notMatches(
888 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
889}
890
891TEST(StatementMatcher, HasDescendant) {
892 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000893 expr(hasType(pointsTo(recordDecl(hasName("X")))),
894 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000895
896 EXPECT_TRUE(matches(
897 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
898 HasDescendantVariableI));
899 EXPECT_TRUE(notMatches(
900 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
901 HasDescendantVariableI));
902}
903
904TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000905 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000906
907 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
908 EXPECT_TRUE(notMatches("class A {};", TypeA));
909
Aaron Ballman512fb642015-09-17 13:30:52 +0000910 TypeMatcher TypeDerivedFromA =
911 hasDeclaration(cxxRecordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000912
913 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
914 TypeDerivedFromA));
915 EXPECT_TRUE(notMatches("class A {};", TypeA));
916
917 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000918 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000919
920 EXPECT_TRUE(
921 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
Aaron Ballmanc129c692015-09-04 18:34:48 +0000922
923 EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }",
924 varDecl(hasType(namedDecl(hasName("S"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000925}
926
Aaron Ballmanb85be662015-09-11 11:51:24 +0000927TEST(TypeMatcher, MatchesDeclTypes) {
928 // TypedefType -> TypedefNameDecl
929 EXPECT_TRUE(matches("typedef int I; void f(I i);",
930 parmVarDecl(hasType(namedDecl(hasName("I"))))));
931 // ObjCObjectPointerType
932 EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);",
933 parmVarDecl(hasType(objcObjectPointerType()))));
934 // ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl
935 EXPECT_TRUE(matchesObjC(
936 "@interface Foo @end void f(Foo *f);",
937 parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo")))))));
938 // TemplateTypeParmType
939 EXPECT_TRUE(matches("template <typename T> void f(T t);",
940 parmVarDecl(hasType(templateTypeParmType()))));
941 // TemplateTypeParmType -> TemplateTypeParmDecl
942 EXPECT_TRUE(matches("template <typename T> void f(T t);",
943 parmVarDecl(hasType(namedDecl(hasName("T"))))));
944 // InjectedClassNameType
945 EXPECT_TRUE(matches("template <typename T> struct S {"
946 " void f(S s);"
947 "};",
948 parmVarDecl(hasType(injectedClassNameType()))));
949 EXPECT_TRUE(notMatches("template <typename T> struct S {"
950 " void g(S<T> s);"
951 "};",
952 parmVarDecl(hasType(injectedClassNameType()))));
953 // InjectedClassNameType -> CXXRecordDecl
954 EXPECT_TRUE(matches("template <typename T> struct S {"
955 " void f(S s);"
956 "};",
957 parmVarDecl(hasType(namedDecl(hasName("S"))))));
958
959 static const char Using[] = "template <typename T>"
960 "struct Base {"
961 " typedef T Foo;"
962 "};"
963 ""
964 "template <typename T>"
965 "struct S : private Base<T> {"
966 " using typename Base<T>::Foo;"
967 " void f(Foo);"
968 "};";
969 // UnresolvedUsingTypenameDecl
970 EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo"))));
971 // UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl
972 EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo"))))));
973}
974
Manuel Klimek04616e42012-07-06 05:48:52 +0000975TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000976 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000977
978 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000979 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000980
981 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000982 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000983
984 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000985 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000986
987 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
988 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000989 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000990
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000991 StatementMatcher MethodX =
Aaron Ballman512fb642015-09-17 13:30:52 +0000992 callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000993
994 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
995 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000996 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000997}
998
999TEST(Matcher, BindTheSameNameInAlternatives) {
1000 StatementMatcher matcher = anyOf(
1001 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001002 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +00001003 hasRHS(integerLiteral(equals(0)))),
1004 binaryOperator(hasOperatorName("+"),
1005 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001006 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001007
1008 EXPECT_TRUE(matchAndVerifyResultTrue(
1009 // The first branch of the matcher binds x to 0 but then fails.
1010 // The second branch binds x to f() and succeeds.
1011 "int f() { return 0 + f(); }",
1012 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00001013 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001014}
1015
Manuel Klimekfdf98762012-08-30 19:41:06 +00001016TEST(Matcher, BindsIDForMemoizedResults) {
1017 // Using the same matcher in two match expressions will make memoization
1018 // kick in.
1019 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
1020 EXPECT_TRUE(matchAndVerifyResultTrue(
1021 "class A { class B { class X {}; }; };",
1022 DeclarationMatcher(anyOf(
1023 recordDecl(hasName("A"), hasDescendant(ClassX)),
1024 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00001025 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +00001026}
1027
Daniel Jasper856194d02012-12-03 15:43:25 +00001028TEST(HasDeclaration, HasDeclarationOfEnumType) {
1029 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
1030 expr(hasType(pointsTo(
1031 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
1032}
1033
Edwin Vaneed936452013-02-25 14:32:42 +00001034TEST(HasDeclaration, HasGetDeclTraitTest) {
1035 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
1036 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
1037 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
1038}
1039
Edwin Vane2c197e02013-02-19 17:14:34 +00001040TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
1041 EXPECT_TRUE(matches("typedef int X; X a;",
1042 varDecl(hasName("a"),
1043 hasType(typedefType(hasDeclaration(decl()))))));
1044
1045 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
1046}
1047
Edwin Vanef901b712013-02-25 14:49:29 +00001048TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
1049 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
1050 varDecl(hasType(templateSpecializationType(
1051 hasDeclaration(namedDecl(hasName("A"))))))));
1052}
1053
Manuel Klimek04616e42012-07-06 05:48:52 +00001054TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001055 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001056 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001057 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001058 EXPECT_TRUE(
1059 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001060 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001061 EXPECT_TRUE(
1062 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001063 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001064}
1065
1066TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001067 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +00001068 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001069 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001070 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001071 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001072 EXPECT_TRUE(
1073 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001074 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001075}
1076
1077TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001078 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001079 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001080 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001081 EXPECT_TRUE(
1082 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001083 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001084}
1085
1086TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001087 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001088 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001089 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001090 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001091 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001092}
1093
Manuel Klimekc16c6522013-06-20 13:08:29 +00001094TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1095 EXPECT_TRUE(matches("int x;",
1096 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1097
1098 // Make sure we don't crash on implicit constructors.
1099 EXPECT_TRUE(notMatches("class X {}; X x;",
1100 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1101}
1102
Manuel Klimek04616e42012-07-06 05:48:52 +00001103TEST(Matcher, Call) {
1104 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001105 // Matcher<Decl>, too?
Aaron Ballman512fb642015-09-17 13:30:52 +00001106 StatementMatcher MethodX =
1107 callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001108
1109 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1110 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1111
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001112 StatementMatcher MethodOnY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001113 cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001114
1115 EXPECT_TRUE(
1116 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1117 MethodOnY));
1118 EXPECT_TRUE(
1119 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1120 MethodOnY));
1121 EXPECT_TRUE(
1122 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1123 MethodOnY));
1124 EXPECT_TRUE(
1125 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1126 MethodOnY));
1127 EXPECT_TRUE(
1128 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1129 MethodOnY));
1130
1131 StatementMatcher MethodOnYPointer =
Aaron Ballman512fb642015-09-17 13:30:52 +00001132 cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001133
1134 EXPECT_TRUE(
1135 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1136 MethodOnYPointer));
1137 EXPECT_TRUE(
1138 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1139 MethodOnYPointer));
1140 EXPECT_TRUE(
1141 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1142 MethodOnYPointer));
1143 EXPECT_TRUE(
1144 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1145 MethodOnYPointer));
1146 EXPECT_TRUE(
1147 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1148 MethodOnYPointer));
1149}
1150
Daniel Jasper5901e472012-10-01 13:40:41 +00001151TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001152 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001153 lambdaExpr()));
1154}
1155
1156TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001157 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1158 "void f() { for (auto &a : as); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001159 cxxForRangeStmt()));
Daniel Jasper5901e472012-10-01 13:40:41 +00001160 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001161 cxxForRangeStmt()));
Daniel Jasper5901e472012-10-01 13:40:41 +00001162}
1163
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001164TEST(Matcher, SubstNonTypeTemplateParm) {
1165 EXPECT_FALSE(matches("template<int N>\n"
1166 "struct A { static const int n = 0; };\n"
1167 "struct B : public A<42> {};",
1168 substNonTypeTemplateParmExpr()));
1169 EXPECT_TRUE(matches("template<int N>\n"
1170 "struct A { static const int n = N; };\n"
1171 "struct B : public A<42> {};",
1172 substNonTypeTemplateParmExpr()));
1173}
1174
Aaron Ballman478a8eb2015-10-05 19:44:42 +00001175TEST(Matcher, NonTypeTemplateParmDecl) {
1176 EXPECT_TRUE(matches("template <int N> void f();",
1177 nonTypeTemplateParmDecl(hasName("N"))));
1178 EXPECT_TRUE(
1179 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
1180}
1181
Eric Fiselier3acf5fd2015-10-17 02:34:44 +00001182TEST(Matcher, templateTypeParmDecl) {
1183 EXPECT_TRUE(matches("template <typename T> void f();",
1184 templateTypeParmDecl(hasName("T"))));
1185 EXPECT_TRUE(
1186 notMatches("template <int N> void f();", templateTypeParmDecl()));
1187}
1188
Daniel Jasper5901e472012-10-01 13:40:41 +00001189TEST(Matcher, UserDefinedLiteral) {
1190 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1191 " return i + 1;"
1192 "}"
1193 "char c = 'a'_inc;",
1194 userDefinedLiteral()));
1195}
1196
Daniel Jasper87c3d362012-09-20 14:12:57 +00001197TEST(Matcher, FlowControl) {
1198 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1199 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1200 continueStmt()));
1201 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1202 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1203 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1204}
1205
Daniel Jasper1dad1832012-07-10 20:20:19 +00001206TEST(HasType, MatchesAsString) {
1207 EXPECT_TRUE(
1208 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001209 cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
1210 EXPECT_TRUE(
1211 matches("class X { void x(int x) {} };",
1212 cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001213 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001214 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001215 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001216 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001217}
1218
Manuel Klimek04616e42012-07-06 05:48:52 +00001219TEST(Matcher, OverloadedOperatorCall) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001220 StatementMatcher OpCall = cxxOperatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001221 // Unary operator
1222 EXPECT_TRUE(matches("class Y { }; "
1223 "bool operator!(Y x) { return false; }; "
1224 "Y y; bool c = !y;", OpCall));
1225 // No match -- special operators like "new", "delete"
1226 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1227 // we need to figure out include paths in the test.
1228 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1229 // "class Y { }; "
1230 // "void *operator new(size_t size) { return 0; } "
1231 // "Y *y = new Y;", OpCall));
1232 EXPECT_TRUE(notMatches("class Y { }; "
1233 "void operator delete(void *p) { } "
1234 "void a() {Y *y = new Y; delete y;}", OpCall));
1235 // Binary operator
1236 EXPECT_TRUE(matches("class Y { }; "
1237 "bool operator&&(Y x, Y y) { return true; }; "
1238 "Y a; Y b; bool c = a && b;",
1239 OpCall));
1240 // No match -- normal operator, not an overloaded one.
1241 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1242 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1243}
1244
1245TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1246 StatementMatcher OpCallAndAnd =
Aaron Ballman512fb642015-09-17 13:30:52 +00001247 cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001248 EXPECT_TRUE(matches("class Y { }; "
1249 "bool operator&&(Y x, Y y) { return true; }; "
1250 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1251 StatementMatcher OpCallLessLess =
Aaron Ballman512fb642015-09-17 13:30:52 +00001252 cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001253 EXPECT_TRUE(notMatches("class Y { }; "
1254 "bool operator&&(Y x, Y y) { return true; }; "
1255 "Y a; Y b; bool c = a && b;",
1256 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001257 StatementMatcher OpStarCall =
Aaron Ballman512fb642015-09-17 13:30:52 +00001258 cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
Benjamin Kramer09514492014-07-14 14:05:02 +00001259 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1260 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001261 DeclarationMatcher ClassWithOpStar =
Aaron Ballman512fb642015-09-17 13:30:52 +00001262 cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001263 EXPECT_TRUE(matches("class Y { int operator*(); };",
1264 ClassWithOpStar));
1265 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1266 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001267 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1268 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1269 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001270}
1271
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001272TEST(Matcher, NestedOverloadedOperatorCalls) {
1273 EXPECT_TRUE(matchAndVerifyResultTrue(
Aaron Ballman512fb642015-09-17 13:30:52 +00001274 "class Y { }; "
1275 "Y& operator&&(Y& x, Y& y) { return x; }; "
1276 "Y a; Y b; Y c; Y d = a && b && c;",
1277 cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1278 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1279 EXPECT_TRUE(matches("class Y { }; "
1280 "Y& operator&&(Y& x, Y& y) { return x; }; "
1281 "Y a; Y b; Y c; Y d = a && b && c;",
1282 cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
1283 EXPECT_TRUE(
1284 matches("class Y { }; "
1285 "Y& operator&&(Y& x, Y& y) { return x; }; "
1286 "Y a; Y b; Y c; Y d = a && b && c;",
1287 cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001288}
1289
Manuel Klimek04616e42012-07-06 05:48:52 +00001290TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001291 StatementMatcher MethodOnY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001292 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001293
1294 EXPECT_TRUE(
1295 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1296 MethodOnY));
1297 EXPECT_TRUE(
1298 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1299 MethodOnY));
1300 EXPECT_TRUE(
1301 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1302 MethodOnY));
1303 EXPECT_TRUE(
1304 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1305 MethodOnY));
1306 EXPECT_TRUE(
1307 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1308 MethodOnY));
1309
1310 EXPECT_TRUE(matches(
1311 "class Y {"
1312 " public: virtual void x();"
1313 "};"
1314 "class X : public Y {"
1315 " public: virtual void x();"
1316 "};"
1317 "void z() { X *x; x->Y::x(); }", MethodOnY));
1318}
1319
1320TEST(Matcher, VariableUsage) {
1321 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001322 declRefExpr(to(
1323 varDecl(hasInitializer(
Aaron Ballman512fb642015-09-17 13:30:52 +00001324 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001325
1326 EXPECT_TRUE(matches(
1327 "class Y {"
1328 " public:"
1329 " bool x() const;"
1330 "};"
1331 "void z(const Y &y) {"
1332 " bool b = y.x();"
1333 " if (b) {}"
1334 "}", Reference));
1335
1336 EXPECT_TRUE(notMatches(
1337 "class Y {"
1338 " public:"
1339 " bool x() const;"
1340 "};"
1341 "void z(const Y &y) {"
1342 " bool b = y.x();"
1343 "}", Reference));
1344}
1345
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001346TEST(Matcher, VarDecl_Storage) {
1347 auto M = varDecl(hasName("X"), hasLocalStorage());
1348 EXPECT_TRUE(matches("void f() { int X; }", M));
1349 EXPECT_TRUE(notMatches("int X;", M));
1350 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1351
1352 M = varDecl(hasName("X"), hasGlobalStorage());
1353 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1354 EXPECT_TRUE(matches("int X;", M));
1355 EXPECT_TRUE(matches("void f() { static int X; }", M));
1356}
1357
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001358TEST(Matcher, VarDecl_StorageDuration) {
1359 std::string T =
Aaron Ballmanf08e1842015-11-18 18:37:29 +00001360 "void f() { int x; static int y; } int a;";
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001361
1362 EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
1363 EXPECT_TRUE(
1364 notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
1365 EXPECT_TRUE(
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001366 notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
1367
1368 EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
1369 EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
1370 EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001371
Aaron Ballmanf08e1842015-11-18 18:37:29 +00001372 // FIXME: It is really hard to test with thread_local itself because not all
1373 // targets support TLS, which causes this to be an error depending on what
1374 // platform the test is being run on. We do not have access to the TargetInfo
1375 // object to be able to test whether the platform supports TLS or not.
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001376 EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
1377 EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
1378 EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
1379}
1380
Manuel Klimek61379422012-12-04 14:42:08 +00001381TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001382 EXPECT_TRUE(matches(
1383 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001384 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001385}
1386
Manuel Klimek04616e42012-07-06 05:48:52 +00001387TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001388 StatementMatcher CallOnVariableY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001389 cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001390
1391 EXPECT_TRUE(matches(
1392 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1393 EXPECT_TRUE(matches(
1394 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1395 EXPECT_TRUE(matches(
1396 "class Y { public: void x(); };"
1397 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1398 EXPECT_TRUE(matches(
1399 "class Y { public: void x(); };"
1400 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1401 EXPECT_TRUE(notMatches(
1402 "class Y { public: void x(); };"
1403 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1404 CallOnVariableY));
1405}
1406
Daniel Jasper1dad1832012-07-10 20:20:19 +00001407TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1408 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1409 unaryExprOrTypeTraitExpr()));
1410 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1411 alignOfExpr(anything())));
1412 // FIXME: Uncomment once alignof is enabled.
1413 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1414 // unaryExprOrTypeTraitExpr()));
1415 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1416 // sizeOfExpr()));
1417}
1418
1419TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1420 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1421 hasArgumentOfType(asString("int")))));
1422 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1423 hasArgumentOfType(asString("float")))));
1424 EXPECT_TRUE(matches(
1425 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001426 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001427 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001428 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001429}
1430
Manuel Klimek04616e42012-07-06 05:48:52 +00001431TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001432 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001433}
1434
1435TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001436 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001437}
1438
1439TEST(MemberExpression, MatchesVariable) {
1440 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001441 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001442 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001443 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001444 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001445 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001446}
1447
1448TEST(MemberExpression, MatchesStaticVariable) {
1449 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001450 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001451 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001452 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001453 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001454 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001455}
1456
Daniel Jasper4e566c42012-07-12 08:50:38 +00001457TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001458 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1459 EXPECT_TRUE(matches(
1460 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1461 callExpr(hasArgument(0, declRefExpr(
1462 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001463}
1464
1465TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001466 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001467 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001468 callExpr(hasArgument(0, declRefExpr(
1469 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001470}
1471
Manuel Klimek04616e42012-07-06 05:48:52 +00001472TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1473 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001474 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001475 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001476 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001477 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001478 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001479}
1480
1481TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1482 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001483 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001484 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001485 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001486 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001487 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001488}
1489
1490TEST(IsArrow, MatchesMemberCallsViaArrow) {
1491 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001492 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001493 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001494 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001495 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001496 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001497}
1498
1499TEST(Callee, MatchesDeclarations) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001500 StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001501
1502 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1503 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001504
Aaron Ballman512fb642015-09-17 13:30:52 +00001505 CallMethodX = callExpr(callee(cxxConversionDecl()));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001506 EXPECT_TRUE(
1507 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1508 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1509 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001510}
1511
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001512TEST(ConversionDeclaration, IsExplicit) {
1513 EXPECT_TRUE(matches("struct S { explicit operator int(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001514 cxxConversionDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001515 EXPECT_TRUE(notMatches("struct S { operator int(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001516 cxxConversionDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001517}
1518
Manuel Klimek04616e42012-07-06 05:48:52 +00001519TEST(Callee, MatchesMemberExpressions) {
1520 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001521 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001522 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001523 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001524}
1525
1526TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001527 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001528
1529 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1530 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1531
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001532 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1533 llvm::Triple::Win32) {
1534 // FIXME: Make this work for MSVC.
1535 // Dependent contexts, but a non-dependent call.
1536 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1537 CallFunctionF));
1538 EXPECT_TRUE(
1539 matches("void f(); template <int N> struct S { void g() { f(); } };",
1540 CallFunctionF));
1541 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001542
1543 // Depedent calls don't match.
1544 EXPECT_TRUE(
1545 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1546 CallFunctionF));
1547 EXPECT_TRUE(
1548 notMatches("void f(int);"
1549 "template <typename T> struct S { void g(T t) { f(t); } };",
1550 CallFunctionF));
Aaron Ballman3fd6c112015-10-05 14:41:27 +00001551
1552 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
1553 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
1554 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
1555 functionDecl(isVariadic())));
1556 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
1557 EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001558}
1559
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001560TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1561 EXPECT_TRUE(
1562 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001563 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001564}
1565
1566TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1567 EXPECT_TRUE(
1568 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001569 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001570}
1571
1572TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1573 EXPECT_TRUE(
1574 notMatches("void g(); template <typename T> void f(T t) {}"
1575 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001576 functionTemplateDecl(hasName("f"),
1577 hasDescendant(declRefExpr(to(
1578 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001579}
1580
Manuel Klimek04616e42012-07-06 05:48:52 +00001581TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001582 StatementMatcher CallArgumentY = callExpr(
1583 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001584
1585 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1586 EXPECT_TRUE(
1587 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1588 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1589
Daniel Jasper848cbe12012-09-18 13:09:13 +00001590 StatementMatcher WrongIndex = callExpr(
1591 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001592 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1593}
1594
1595TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001596 StatementMatcher CallArgumentY = callExpr(
1597 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001598 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1599 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1600 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1601}
1602
1603TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001604 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001605
1606 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1607 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1608 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1609}
1610
Daniel Jasper9f501292012-12-04 11:54:27 +00001611TEST(Matcher, ParameterCount) {
1612 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1613 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1614 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1615 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1616 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1617}
1618
Manuel Klimek04616e42012-07-06 05:48:52 +00001619TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001620 DeclarationMatcher ReferenceClassX = varDecl(
1621 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001622 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1623 ReferenceClassX));
1624 EXPECT_TRUE(
1625 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001626 // The match here is on the implicit copy constructor code for
1627 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001628 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001629 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1630 EXPECT_TRUE(
1631 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001632 EXPECT_TRUE(
1633 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1634}
1635
Edwin Vane0a4836e2013-03-06 17:02:57 +00001636TEST(QualType, hasCanonicalType) {
1637 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1638 "int a;"
1639 "int_ref b = a;",
1640 varDecl(hasType(qualType(referenceType())))));
1641 EXPECT_TRUE(
1642 matches("typedef int &int_ref;"
1643 "int a;"
1644 "int_ref b = a;",
1645 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1646}
1647
Edwin Vane119d3df2013-04-02 18:15:55 +00001648TEST(QualType, hasLocalQualifiers) {
1649 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1650 varDecl(hasType(hasLocalQualifiers()))));
1651 EXPECT_TRUE(matches("int *const j = nullptr;",
1652 varDecl(hasType(hasLocalQualifiers()))));
1653 EXPECT_TRUE(matches("int *volatile k;",
1654 varDecl(hasType(hasLocalQualifiers()))));
1655 EXPECT_TRUE(notMatches("int m;",
1656 varDecl(hasType(hasLocalQualifiers()))));
1657}
1658
Manuel Klimek04616e42012-07-06 05:48:52 +00001659TEST(HasParameter, CallsInnerMatcher) {
1660 EXPECT_TRUE(matches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001661 cxxMethodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001662 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001663 cxxMethodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001664}
1665
1666TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1667 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001668 cxxMethodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001669}
1670
1671TEST(HasType, MatchesParameterVariableTypesStrictly) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001672 EXPECT_TRUE(matches(
1673 "class X { void x(X x) {} };",
1674 cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
1675 EXPECT_TRUE(notMatches(
1676 "class X { void x(const X &x) {} };",
1677 cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001678 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001679 cxxMethodDecl(hasParameter(
1680 0, hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001681 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001682 cxxMethodDecl(hasParameter(
1683 0, hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001684}
1685
1686TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001687 EXPECT_TRUE(matches(
1688 "class Y {}; class X { void x(X x, Y y) {} };",
1689 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
1690 EXPECT_TRUE(matches(
1691 "class Y {}; class X { void x(Y y, X x) {} };",
1692 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001693}
1694
Daniel Jasper1dad1832012-07-10 20:20:19 +00001695TEST(Returns, MatchesReturnTypes) {
1696 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001697 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001698 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001699 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001700 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001701 functionDecl(returns(hasDeclaration(
1702 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001703}
1704
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001705TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001706 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1707 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1708 functionDecl(isExternC())));
1709 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001710}
1711
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001712TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1713 EXPECT_TRUE(
1714 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1715 EXPECT_TRUE(matches("void Func() = delete;",
1716 functionDecl(hasName("Func"), isDeleted())));
1717}
1718
Aaron Ballmana60bcda2015-12-02 15:23:59 +00001719TEST(IsNoThrow, MatchesNoThrowFunctionDeclarations) {
1720 EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
1721 EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
1722 EXPECT_TRUE(
1723 notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
1724 EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
1725 EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
1726}
1727
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001728TEST(isConstexpr, MatchesConstexprDeclarations) {
1729 EXPECT_TRUE(matches("constexpr int foo = 42;",
1730 varDecl(hasName("foo"), isConstexpr())));
1731 EXPECT_TRUE(matches("constexpr int bar();",
1732 functionDecl(hasName("bar"), isConstexpr())));
1733}
1734
Manuel Klimek04616e42012-07-06 05:48:52 +00001735TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001736 EXPECT_TRUE(notMatches(
1737 "class Y {}; class X { void x(int) {} };",
1738 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001739}
1740
1741TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1742 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001743 cxxMethodDecl(hasAnyParameter(
1744 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001745}
1746
Alp Toker8db6e7a2014-01-05 06:38:57 +00001747TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001748 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001749 cxxMethodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001750 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001751 cxxMethodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001752}
1753
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001754TEST(Matcher, MatchesClassTemplateSpecialization) {
1755 EXPECT_TRUE(matches("template<typename T> struct A {};"
1756 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001757 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001758 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001759 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001760 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001761 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001762}
1763
Manuel Klimekc16c6522013-06-20 13:08:29 +00001764TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1765 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1766 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1767}
1768
1769TEST(ParmVarDecl, MatchesParmVars) {
1770 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1771 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1772}
1773
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001774TEST(Matcher, MatchesTypeTemplateArgument) {
1775 EXPECT_TRUE(matches(
1776 "template<typename T> struct B {};"
1777 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001778 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001779 asString("int"))))));
1780}
1781
1782TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1783 EXPECT_TRUE(matches(
1784 "struct B { int next; };"
1785 "template<int(B::*next_ptr)> struct A {};"
1786 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001787 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1788 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001789
1790 EXPECT_TRUE(notMatches(
1791 "template <typename T> struct A {};"
1792 "A<int> a;",
1793 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1794 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001795
1796 EXPECT_TRUE(matches(
1797 "struct B { int next; };"
1798 "template<int(B::*next_ptr)> struct A {};"
1799 "A<&B::next> a;",
1800 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1801 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1802
1803 EXPECT_TRUE(notMatches(
1804 "template <typename T> struct A {};"
1805 "A<int> a;",
1806 templateSpecializationType(hasAnyTemplateArgument(
1807 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001808}
1809
1810TEST(Matcher, MatchesSpecificArgument) {
1811 EXPECT_TRUE(matches(
1812 "template<typename T, typename U> class A {};"
1813 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001814 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001815 1, refersToType(asString("int"))))));
1816 EXPECT_TRUE(notMatches(
1817 "template<typename T, typename U> class A {};"
1818 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001819 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001820 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001821
1822 EXPECT_TRUE(matches(
1823 "template<typename T, typename U> class A {};"
1824 "A<bool, int> a;",
1825 templateSpecializationType(hasTemplateArgument(
1826 1, refersToType(asString("int"))))));
1827 EXPECT_TRUE(notMatches(
1828 "template<typename T, typename U> class A {};"
1829 "A<int, bool> a;",
1830 templateSpecializationType(hasTemplateArgument(
1831 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001832}
1833
Manuel Klimek7735e402014-10-09 13:06:22 +00001834TEST(TemplateArgument, Matches) {
1835 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1836 classTemplateSpecializationDecl(
1837 hasAnyTemplateArgument(templateArgument()))));
1838 EXPECT_TRUE(matches(
1839 "template<typename T> struct C {}; C<int> c;",
1840 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1841}
1842
1843TEST(TemplateArgumentCountIs, Matches) {
1844 EXPECT_TRUE(
1845 matches("template<typename T> struct C {}; C<int> c;",
1846 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1847 EXPECT_TRUE(
1848 notMatches("template<typename T> struct C {}; C<int> c;",
1849 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1850
1851 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1852 templateSpecializationType(templateArgumentCountIs(1))));
1853 EXPECT_TRUE(
1854 notMatches("template<typename T> struct C {}; C<int> c;",
1855 templateSpecializationType(templateArgumentCountIs(2))));
1856}
1857
1858TEST(IsIntegral, Matches) {
1859 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1860 classTemplateSpecializationDecl(
1861 hasAnyTemplateArgument(isIntegral()))));
1862 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1863 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1864 templateArgument(isIntegral())))));
1865}
1866
1867TEST(RefersToIntegralType, Matches) {
1868 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1869 classTemplateSpecializationDecl(
1870 hasAnyTemplateArgument(refersToIntegralType(
1871 asString("int"))))));
1872 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1873 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1874 refersToIntegralType(asString("int"))))));
1875}
1876
1877TEST(EqualsIntegralValue, Matches) {
1878 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1879 classTemplateSpecializationDecl(
1880 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1881 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1882 classTemplateSpecializationDecl(
1883 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1884 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1885 classTemplateSpecializationDecl(
1886 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1887 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1888 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1889 equalsIntegralValue("0042")))));
1890}
1891
Daniel Jasper639522c2013-02-25 12:02:08 +00001892TEST(Matcher, MatchesAccessSpecDecls) {
1893 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1894 EXPECT_TRUE(
1895 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1896 EXPECT_TRUE(
1897 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1898 EXPECT_TRUE(
1899 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1900
1901 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1902}
1903
Aaron Ballman41143bb2015-07-24 12:35:41 +00001904TEST(Matcher, MatchesFinal) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001905 EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
Aaron Ballman41143bb2015-07-24 12:35:41 +00001906 EXPECT_TRUE(matches("class X { virtual void f() final; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001907 cxxMethodDecl(isFinal())));
1908 EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
1909 EXPECT_TRUE(
1910 notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
Aaron Ballman41143bb2015-07-24 12:35:41 +00001911}
1912
Edwin Vane37ee1d72013-04-09 20:46:36 +00001913TEST(Matcher, MatchesVirtualMethod) {
1914 EXPECT_TRUE(matches("class X { virtual int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001915 cxxMethodDecl(isVirtual(), hasName("::X::f"))));
1916 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001917}
1918
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001919TEST(Matcher, MatchesPureMethod) {
1920 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001921 cxxMethodDecl(isPure(), hasName("::X::f"))));
1922 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001923}
1924
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00001925TEST(Matcher, MatchesCopyAssignmentOperator) {
1926 EXPECT_TRUE(matches("class X { X &operator=(X); };",
1927 cxxMethodDecl(isCopyAssignmentOperator())));
1928 EXPECT_TRUE(matches("class X { X &operator=(X &); };",
1929 cxxMethodDecl(isCopyAssignmentOperator())));
1930 EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
1931 cxxMethodDecl(isCopyAssignmentOperator())));
1932 EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
1933 cxxMethodDecl(isCopyAssignmentOperator())));
1934 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
1935 cxxMethodDecl(isCopyAssignmentOperator())));
1936 EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
1937 cxxMethodDecl(isCopyAssignmentOperator())));
1938}
1939
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001940TEST(Matcher, MatchesConstMethod) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001941 EXPECT_TRUE(
1942 matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
1943 EXPECT_TRUE(
1944 notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001945}
1946
Edwin Vane37ee1d72013-04-09 20:46:36 +00001947TEST(Matcher, MatchesOverridingMethod) {
1948 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1949 "class Y : public X { int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001950 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001951 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
Aaron Ballman512fb642015-09-17 13:30:52 +00001952 "class Y : public X { int f(); };",
1953 cxxMethodDecl(isOverride(), hasName("::X::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001954 EXPECT_TRUE(notMatches("class X { int f(); }; "
1955 "class Y : public X { int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001956 cxxMethodDecl(isOverride())));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001957 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
Aaron Ballman512fb642015-09-17 13:30:52 +00001958 cxxMethodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00001959 EXPECT_TRUE(
1960 matches("template <typename Base> struct Y : Base { void f() override;};",
Aaron Ballman512fb642015-09-17 13:30:52 +00001961 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00001962}
1963
Manuel Klimek04616e42012-07-06 05:48:52 +00001964TEST(Matcher, ConstructorCall) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001965 StatementMatcher Constructor = cxxConstructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001966
1967 EXPECT_TRUE(
1968 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1969 EXPECT_TRUE(
1970 matches("class X { public: X(); }; void x() { X x = X(); }",
1971 Constructor));
1972 EXPECT_TRUE(
1973 matches("class X { public: X(int); }; void x() { X x = 0; }",
1974 Constructor));
1975 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1976}
1977
1978TEST(Matcher, ConstructorArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001979 StatementMatcher Constructor = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00001980 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001981
1982 EXPECT_TRUE(
1983 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1984 Constructor));
1985 EXPECT_TRUE(
1986 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1987 Constructor));
1988 EXPECT_TRUE(
1989 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1990 Constructor));
1991 EXPECT_TRUE(
1992 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1993 Constructor));
1994
Aaron Ballman512fb642015-09-17 13:30:52 +00001995 StatementMatcher WrongIndex = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00001996 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001997 EXPECT_TRUE(
1998 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1999 WrongIndex));
2000}
2001
2002TEST(Matcher, ConstructorArgumentCount) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002003 StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002004
2005 EXPECT_TRUE(
2006 matches("class X { public: X(int); }; void x() { X x(0); }",
2007 Constructor1Arg));
2008 EXPECT_TRUE(
2009 matches("class X { public: X(int); }; void x() { X x = X(0); }",
2010 Constructor1Arg));
2011 EXPECT_TRUE(
2012 matches("class X { public: X(int); }; void x() { X x = 0; }",
2013 Constructor1Arg));
2014 EXPECT_TRUE(
2015 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
2016 Constructor1Arg));
2017}
2018
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00002019TEST(Matcher, ConstructorListInitialization) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002020 StatementMatcher ConstructorListInit =
2021 cxxConstructExpr(isListInitialization());
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00002022
2023 EXPECT_TRUE(
2024 matches("class X { public: X(int); }; void x() { X x{0}; }",
2025 ConstructorListInit));
2026 EXPECT_FALSE(
2027 matches("class X { public: X(int); }; void x() { X x(0); }",
2028 ConstructorListInit));
2029}
2030
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002031TEST(Matcher,ThisExpr) {
2032 EXPECT_TRUE(
Aaron Ballman512fb642015-09-17 13:30:52 +00002033 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002034 EXPECT_TRUE(
Aaron Ballman512fb642015-09-17 13:30:52 +00002035 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002036}
2037
Manuel Klimek04616e42012-07-06 05:48:52 +00002038TEST(Matcher, BindTemporaryExpression) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002039 StatementMatcher TempExpression = cxxBindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002040
2041 std::string ClassString = "class string { public: string(); ~string(); }; ";
2042
2043 EXPECT_TRUE(
2044 matches(ClassString +
2045 "string GetStringByValue();"
2046 "void FunctionTakesString(string s);"
2047 "void run() { FunctionTakesString(GetStringByValue()); }",
2048 TempExpression));
2049
2050 EXPECT_TRUE(
2051 notMatches(ClassString +
2052 "string* GetStringPointer(); "
2053 "void FunctionTakesStringPtr(string* s);"
2054 "void run() {"
2055 " string* s = GetStringPointer();"
2056 " FunctionTakesStringPtr(GetStringPointer());"
2057 " FunctionTakesStringPtr(s);"
2058 "}",
2059 TempExpression));
2060
2061 EXPECT_TRUE(
2062 notMatches("class no_dtor {};"
2063 "no_dtor GetObjByValue();"
2064 "void ConsumeObj(no_dtor param);"
2065 "void run() { ConsumeObj(GetObjByValue()); }",
2066 TempExpression));
2067}
2068
Sam Panzer68a35af2012-08-24 22:04:44 +00002069TEST(MaterializeTemporaryExpr, MatchesTemporary) {
2070 std::string ClassString =
2071 "class string { public: string(); int length(); }; ";
2072
2073 EXPECT_TRUE(
2074 matches(ClassString +
2075 "string GetStringByValue();"
2076 "void FunctionTakesString(string s);"
2077 "void run() { FunctionTakesString(GetStringByValue()); }",
2078 materializeTemporaryExpr()));
2079
2080 EXPECT_TRUE(
2081 notMatches(ClassString +
2082 "string* GetStringPointer(); "
2083 "void FunctionTakesStringPtr(string* s);"
2084 "void run() {"
2085 " string* s = GetStringPointer();"
2086 " FunctionTakesStringPtr(GetStringPointer());"
2087 " FunctionTakesStringPtr(s);"
2088 "}",
2089 materializeTemporaryExpr()));
2090
2091 EXPECT_TRUE(
2092 notMatches(ClassString +
2093 "string GetStringByValue();"
2094 "void run() { int k = GetStringByValue().length(); }",
2095 materializeTemporaryExpr()));
2096
2097 EXPECT_TRUE(
2098 notMatches(ClassString +
2099 "string GetStringByValue();"
2100 "void run() { GetStringByValue(); }",
2101 materializeTemporaryExpr()));
2102}
2103
Manuel Klimek04616e42012-07-06 05:48:52 +00002104TEST(ConstructorDeclaration, SimpleCase) {
2105 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002106 cxxConstructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002107 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002108 cxxConstructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002109}
2110
2111TEST(ConstructorDeclaration, IsImplicit) {
2112 // This one doesn't match because the constructor is not added by the
2113 // compiler (it is not needed).
2114 EXPECT_TRUE(notMatches("class Foo { };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002115 cxxConstructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002116 // The compiler added the implicit default constructor.
2117 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Aaron Ballman512fb642015-09-17 13:30:52 +00002118 cxxConstructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002119 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002120 cxxConstructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00002121 // The compiler added an implicit assignment operator.
2122 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002123 cxxMethodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002124}
2125
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002126TEST(ConstructorDeclaration, IsExplicit) {
2127 EXPECT_TRUE(matches("struct S { explicit S(int); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002128 cxxConstructorDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002129 EXPECT_TRUE(notMatches("struct S { S(int); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002130 cxxConstructorDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002131}
2132
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002133TEST(ConstructorDeclaration, Kinds) {
2134 EXPECT_TRUE(matches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002135 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002136 EXPECT_TRUE(notMatches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002137 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002138 EXPECT_TRUE(notMatches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002139 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002140
2141 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002142 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002143 EXPECT_TRUE(matches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002144 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002145 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002146 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002147
2148 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002149 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002150 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002151 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002152 EXPECT_TRUE(matches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002153 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002154}
2155
Daniel Jasper1dad1832012-07-10 20:20:19 +00002156TEST(DestructorDeclaration, MatchesVirtualDestructor) {
2157 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002158 cxxDestructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002159}
2160
2161TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002162 EXPECT_TRUE(notMatches("class Foo {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00002163 cxxDestructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002164}
2165
Manuel Klimek04616e42012-07-06 05:48:52 +00002166TEST(HasAnyConstructorInitializer, SimpleCase) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002167 EXPECT_TRUE(
2168 notMatches("class Foo { Foo() { } };",
2169 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
2170 EXPECT_TRUE(
2171 matches("class Foo {"
2172 " Foo() : foo_() { }"
2173 " int foo_;"
2174 "};",
2175 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002176}
2177
2178TEST(HasAnyConstructorInitializer, ForField) {
2179 static const char Code[] =
2180 "class Baz { };"
2181 "class Foo {"
2182 " Foo() : foo_() { }"
2183 " Baz foo_;"
2184 " Baz bar_;"
2185 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002186 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002187 forField(hasType(recordDecl(hasName("Baz"))))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002188 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002189 forField(hasName("foo_"))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002190 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002191 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002192}
2193
2194TEST(HasAnyConstructorInitializer, WithInitializer) {
2195 static const char Code[] =
2196 "class Foo {"
2197 " Foo() : foo_(0) { }"
2198 " int foo_;"
2199 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002200 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002201 withInitializer(integerLiteral(equals(0)))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002202 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002203 withInitializer(integerLiteral(equals(1)))))));
2204}
2205
2206TEST(HasAnyConstructorInitializer, IsWritten) {
2207 static const char Code[] =
2208 "struct Bar { Bar(){} };"
2209 "class Foo {"
2210 " Foo() : foo_() { }"
2211 " Bar foo_;"
2212 " Bar bar_;"
2213 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002214 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002215 allOf(forField(hasName("foo_")), isWritten())))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002216 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002217 allOf(forField(hasName("bar_")), isWritten())))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002218 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002219 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2220}
2221
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002222TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
2223 static const char Code[] =
2224 "struct B {};"
2225 "struct D : B {"
2226 " int I;"
2227 " D(int i) : I(i) {}"
2228 "};"
2229 "struct E : B {"
2230 " E() : B() {}"
2231 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002232 EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002233 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2234 hasName("E")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002235 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002236 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2237 hasName("D")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002238 EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
Aaron Ballmaned455d42015-08-11 20:42:00 +00002239 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2240 hasName("D")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002241 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
Aaron Ballmaned455d42015-08-11 20:42:00 +00002242 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2243 hasName("E")))));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002244}
2245
Manuel Klimek04616e42012-07-06 05:48:52 +00002246TEST(Matcher, NewExpression) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002247 StatementMatcher New = cxxNewExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002248
2249 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2250 EXPECT_TRUE(
2251 matches("class X { public: X(); }; void x() { new X(); }", New));
2252 EXPECT_TRUE(
2253 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2254 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2255}
2256
2257TEST(Matcher, NewExpressionArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002258 StatementMatcher New = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002259 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002260
2261 EXPECT_TRUE(
2262 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2263 New));
2264 EXPECT_TRUE(
2265 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2266 New));
2267 EXPECT_TRUE(
2268 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2269 New));
2270
Aaron Ballman512fb642015-09-17 13:30:52 +00002271 StatementMatcher WrongIndex = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002272 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002273 EXPECT_TRUE(
2274 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2275 WrongIndex));
2276}
2277
2278TEST(Matcher, NewExpressionArgumentCount) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002279 StatementMatcher New = cxxConstructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002280
2281 EXPECT_TRUE(
2282 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2283 EXPECT_TRUE(
2284 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2285 New));
2286}
2287
Daniel Jasper1dad1832012-07-10 20:20:19 +00002288TEST(Matcher, DeleteExpression) {
2289 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002290 cxxDeleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002291}
2292
Manuel Klimek04616e42012-07-06 05:48:52 +00002293TEST(Matcher, DefaultArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002294 StatementMatcher Arg = cxxDefaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002295
2296 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2297 EXPECT_TRUE(
2298 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2299 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2300}
2301
2302TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002303 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002304 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2305 // wide string
2306 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2307 // with escaped characters
2308 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2309 // no matching -- though the data type is the same, there is no string literal
2310 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2311}
2312
2313TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002314 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002315 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2316 // wide character
2317 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2318 // wide character, Hex encoded, NOT MATCHED!
2319 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2320 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2321}
2322
2323TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002324 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002325 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2326 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2327 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2328 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2329
2330 // Non-matching cases (character literals, float and double)
2331 EXPECT_TRUE(notMatches("int i = L'a';",
2332 HasIntLiteral)); // this is actually a character
2333 // literal cast to int
2334 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2335 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2336 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2337}
2338
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002339TEST(Matcher, FloatLiterals) {
2340 StatementMatcher HasFloatLiteral = floatLiteral();
2341 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2342 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2343 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2344 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2345 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002346 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2347 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2348 EXPECT_TRUE(
2349 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002350
2351 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002352 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2353 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2354 EXPECT_TRUE(
2355 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002356}
2357
Daniel Jasper5901e472012-10-01 13:40:41 +00002358TEST(Matcher, NullPtrLiteral) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002359 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
Daniel Jasper5901e472012-10-01 13:40:41 +00002360}
2361
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002362TEST(Matcher, GNUNullExpr) {
2363 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2364}
2365
Daniel Jasper87c3d362012-09-20 14:12:57 +00002366TEST(Matcher, AsmStatement) {
2367 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2368}
2369
Manuel Klimek04616e42012-07-06 05:48:52 +00002370TEST(Matcher, Conditions) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002371 StatementMatcher Condition =
2372 ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002373
2374 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2375 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2376 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2377 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2378 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2379}
2380
Manuel Klimek909b5c942014-05-27 10:04:12 +00002381TEST(IfStmt, ChildTraversalMatchers) {
2382 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002383 ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002384 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002385 ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002386 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002387 ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002388 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002389 ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002390}
2391
Manuel Klimek04616e42012-07-06 05:48:52 +00002392TEST(MatchBinaryOperator, HasOperatorName) {
2393 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2394
2395 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2396 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2397}
2398
2399TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2400 StatementMatcher OperatorTrueFalse =
Aaron Ballman512fb642015-09-17 13:30:52 +00002401 binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
2402 hasRHS(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002403
2404 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2405 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2406 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
Alexander Kornienkoe39993e2015-11-02 22:23:21 +00002407
2408 StatementMatcher OperatorIntPointer = arraySubscriptExpr(
2409 hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
2410 EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
2411 EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
Manuel Klimek04616e42012-07-06 05:48:52 +00002412}
2413
2414TEST(MatchBinaryOperator, HasEitherOperand) {
2415 StatementMatcher HasOperand =
Aaron Ballman512fb642015-09-17 13:30:52 +00002416 binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002417
2418 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2419 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2420 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2421}
2422
2423TEST(Matcher, BinaryOperatorTypes) {
2424 // Integration test that verifies the AST provides all binary operators in
2425 // a way we expect.
2426 // FIXME: Operator ','
2427 EXPECT_TRUE(
2428 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2429 EXPECT_TRUE(
2430 matches("bool b; bool c = (b = true);",
2431 binaryOperator(hasOperatorName("="))));
2432 EXPECT_TRUE(
2433 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2434 EXPECT_TRUE(
2435 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2436 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2437 EXPECT_TRUE(
2438 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2439 EXPECT_TRUE(
2440 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2441 EXPECT_TRUE(
2442 matches("int i = 1; int j = (i <<= 2);",
2443 binaryOperator(hasOperatorName("<<="))));
2444 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2445 EXPECT_TRUE(
2446 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2447 EXPECT_TRUE(
2448 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2449 EXPECT_TRUE(
2450 matches("int i = 1; int j = (i >>= 2);",
2451 binaryOperator(hasOperatorName(">>="))));
2452 EXPECT_TRUE(
2453 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2454 EXPECT_TRUE(
2455 matches("int i = 42; int j = (i ^= 42);",
2456 binaryOperator(hasOperatorName("^="))));
2457 EXPECT_TRUE(
2458 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2459 EXPECT_TRUE(
2460 matches("int i = 42; int j = (i %= 42);",
2461 binaryOperator(hasOperatorName("%="))));
2462 EXPECT_TRUE(
2463 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2464 EXPECT_TRUE(
2465 matches("bool b = true && false;",
2466 binaryOperator(hasOperatorName("&&"))));
2467 EXPECT_TRUE(
2468 matches("bool b = true; bool c = (b &= false);",
2469 binaryOperator(hasOperatorName("&="))));
2470 EXPECT_TRUE(
2471 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2472 EXPECT_TRUE(
2473 matches("bool b = true || false;",
2474 binaryOperator(hasOperatorName("||"))));
2475 EXPECT_TRUE(
2476 matches("bool b = true; bool c = (b |= false);",
2477 binaryOperator(hasOperatorName("|="))));
2478 EXPECT_TRUE(
2479 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2480 EXPECT_TRUE(
2481 matches("int i = 42; int j = (i *= 23);",
2482 binaryOperator(hasOperatorName("*="))));
2483 EXPECT_TRUE(
2484 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2485 EXPECT_TRUE(
2486 matches("int i = 42; int j = (i /= 23);",
2487 binaryOperator(hasOperatorName("/="))));
2488 EXPECT_TRUE(
2489 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2490 EXPECT_TRUE(
2491 matches("int i = 42; int j = (i += 23);",
2492 binaryOperator(hasOperatorName("+="))));
2493 EXPECT_TRUE(
2494 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2495 EXPECT_TRUE(
2496 matches("int i = 42; int j = (i -= 23);",
2497 binaryOperator(hasOperatorName("-="))));
2498 EXPECT_TRUE(
2499 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2500 binaryOperator(hasOperatorName("->*"))));
2501 EXPECT_TRUE(
2502 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2503 binaryOperator(hasOperatorName(".*"))));
2504
2505 // Member expressions as operators are not supported in matches.
2506 EXPECT_TRUE(
2507 notMatches("struct A { void x(A *a) { a->x(this); } };",
2508 binaryOperator(hasOperatorName("->"))));
2509
2510 // Initializer assignments are not represented as operator equals.
2511 EXPECT_TRUE(
2512 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2513
2514 // Array indexing is not represented as operator.
2515 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2516
2517 // Overloaded operators do not match at all.
2518 EXPECT_TRUE(notMatches(
2519 "struct A { bool operator&&(const A &a) const { return false; } };"
2520 "void x() { A a, b; a && b; }",
2521 binaryOperator()));
2522}
2523
2524TEST(MatchUnaryOperator, HasOperatorName) {
2525 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2526
2527 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2528 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2529}
2530
2531TEST(MatchUnaryOperator, HasUnaryOperand) {
2532 StatementMatcher OperatorOnFalse =
Aaron Ballman512fb642015-09-17 13:30:52 +00002533 unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002534
2535 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2536 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2537}
2538
2539TEST(Matcher, UnaryOperatorTypes) {
2540 // Integration test that verifies the AST provides all unary operators in
2541 // a way we expect.
2542 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2543 EXPECT_TRUE(
2544 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2545 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2546 EXPECT_TRUE(
2547 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2548 EXPECT_TRUE(
2549 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2550 EXPECT_TRUE(
2551 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2552 EXPECT_TRUE(
2553 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2554 EXPECT_TRUE(
2555 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2556 EXPECT_TRUE(
2557 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2558 EXPECT_TRUE(
2559 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2560
2561 // We don't match conversion operators.
2562 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2563
2564 // Function calls are not represented as operator.
2565 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2566
2567 // Overloaded operators do not match at all.
2568 // FIXME: We probably want to add that.
2569 EXPECT_TRUE(notMatches(
2570 "struct A { bool operator!() const { return false; } };"
2571 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2572}
2573
2574TEST(Matcher, ConditionalOperator) {
2575 StatementMatcher Conditional = conditionalOperator(
Aaron Ballman512fb642015-09-17 13:30:52 +00002576 hasCondition(cxxBoolLiteral(equals(true))),
2577 hasTrueExpression(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002578
2579 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2580 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2581 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2582
2583 StatementMatcher ConditionalFalse = conditionalOperator(
Aaron Ballman512fb642015-09-17 13:30:52 +00002584 hasFalseExpression(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002585
2586 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2587 EXPECT_TRUE(
2588 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2589}
2590
Daniel Jasper1dad1832012-07-10 20:20:19 +00002591TEST(ArraySubscriptMatchers, ArraySubscripts) {
2592 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2593 arraySubscriptExpr()));
2594 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2595 arraySubscriptExpr()));
2596}
2597
2598TEST(ArraySubscriptMatchers, ArrayIndex) {
2599 EXPECT_TRUE(matches(
2600 "int i[2]; void f() { i[1] = 1; }",
2601 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2602 EXPECT_TRUE(matches(
2603 "int i[2]; void f() { 1[i] = 1; }",
2604 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2605 EXPECT_TRUE(notMatches(
2606 "int i[2]; void f() { i[1] = 1; }",
2607 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2608}
2609
2610TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2611 EXPECT_TRUE(matches(
2612 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002613 arraySubscriptExpr(hasBase(implicitCastExpr(
2614 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002615}
2616
Manuel Klimek04616e42012-07-06 05:48:52 +00002617TEST(Matcher, HasNameSupportsNamespaces) {
2618 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002619 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002620 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002621 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002622 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002623 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002624 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002625 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002626 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002627 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002628 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002629 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002630 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002631 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002632 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002633 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002634 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002635 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002636 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002637 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002638 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002639 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002640 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002641 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002642}
2643
2644TEST(Matcher, HasNameSupportsOuterClasses) {
2645 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002646 matches("class A { class B { class C; }; };",
2647 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002648 EXPECT_TRUE(
2649 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002650 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002651 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002652 matches("class A { class B { class C; }; };",
2653 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002654 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002655 matches("class A { class B { class C; }; };",
2656 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002657 EXPECT_TRUE(
2658 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002659 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002660 EXPECT_TRUE(
2661 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002662 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002663 EXPECT_TRUE(
2664 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002665 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002666 EXPECT_TRUE(
2667 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002668 recordDecl(hasName("::C"))));
2669 EXPECT_TRUE(
2670 notMatches("class A { class B { class C; }; };",
2671 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002672 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002673 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002674 EXPECT_TRUE(
2675 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002676 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002677}
2678
2679TEST(Matcher, IsDefinition) {
2680 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002681 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002682 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2683 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2684
2685 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002686 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002687 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2688 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2689
2690 DeclarationMatcher DefinitionOfMethodA =
Aaron Ballman512fb642015-09-17 13:30:52 +00002691 cxxMethodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002692 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2693 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2694}
2695
2696TEST(Matcher, OfClass) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002697 StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002698 ofClass(hasName("X")))));
2699
2700 EXPECT_TRUE(
2701 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2702 EXPECT_TRUE(
2703 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2704 Constructor));
2705 EXPECT_TRUE(
2706 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2707 Constructor));
2708}
2709
2710TEST(Matcher, VisitsTemplateInstantiations) {
2711 EXPECT_TRUE(matches(
2712 "class A { public: void x(); };"
2713 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002714 "void f() { B<A> b; b.y(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002715 callExpr(callee(cxxMethodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002716
2717 EXPECT_TRUE(matches(
2718 "class A { public: void x(); };"
2719 "class C {"
2720 " public:"
2721 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2722 "};"
2723 "void f() {"
2724 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002725 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00002726 recordDecl(hasName("C"), hasDescendant(callExpr(
2727 callee(cxxMethodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002728}
2729
Daniel Jasper1dad1832012-07-10 20:20:19 +00002730TEST(Matcher, HandlesNullQualTypes) {
2731 // FIXME: Add a Type matcher so we can replace uses of this
2732 // variable with Type(True())
2733 const TypeMatcher AnyType = anything();
2734
2735 // We don't really care whether this matcher succeeds; we're testing that
2736 // it completes without crashing.
2737 EXPECT_TRUE(matches(
2738 "struct A { };"
2739 "template <typename T>"
2740 "void f(T t) {"
2741 " T local_t(t /* this becomes a null QualType in the AST */);"
2742 "}"
2743 "void g() {"
2744 " f(0);"
2745 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002746 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002747 anyOf(
2748 TypeMatcher(hasDeclaration(anything())),
2749 pointsTo(AnyType),
2750 references(AnyType)
2751 // Other QualType matchers should go here.
2752 ))))));
2753}
2754
Manuel Klimek04616e42012-07-06 05:48:52 +00002755// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002756AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002757 // Make sure all special variables are used: node, match_finder,
2758 // bound_nodes_builder, and the parameter named 'AMatcher'.
2759 return AMatcher.matches(Node, Finder, Builder);
2760}
2761
2762TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002763 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002764
2765 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002766 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002767
2768 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002769 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002770
2771 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002772 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002773}
2774
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002775AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2776 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2777 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002778 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002779 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002780 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2781 ASTMatchFinder::BK_First);
2782}
2783
2784TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002785 DeclarationMatcher HasClassB =
2786 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002787
2788 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002789 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002790
2791 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002792 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002793
2794 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002795 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002796
2797 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002798 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002799
2800 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2801}
2802
2803TEST(For, FindsForLoops) {
2804 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2805 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002806 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2807 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002808 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002809}
2810
Daniel Jasper4e566c42012-07-12 08:50:38 +00002811TEST(For, ForLoopInternals) {
2812 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2813 forStmt(hasCondition(anything()))));
2814 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2815 forStmt(hasLoopInit(anything()))));
2816}
2817
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002818TEST(For, ForRangeLoopInternals) {
2819 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002820 cxxForRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002821 EXPECT_TRUE(matches(
2822 "void f(){ int a[] {1, 2}; for (int i : a); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002823 cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002824}
2825
Daniel Jasper4e566c42012-07-12 08:50:38 +00002826TEST(For, NegativeForLoopInternals) {
2827 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002828 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002829 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2830 forStmt(hasLoopInit(anything()))));
2831}
2832
Manuel Klimek04616e42012-07-06 05:48:52 +00002833TEST(For, ReportsNoFalsePositives) {
2834 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2835 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2836}
2837
2838TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002839 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2840 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2841 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002842}
2843
2844TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2845 // It's not a compound statement just because there's "{}" in the source
2846 // text. This is an AST search, not grep.
2847 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002848 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002849 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002850 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002851}
2852
Daniel Jasper4e566c42012-07-12 08:50:38 +00002853TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002854 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002855 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002856 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002857 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002858 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002859 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002860 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002861 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002862 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002863 cxxForRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002864}
2865
2866TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2867 // The simplest case: every compound statement is in a function
2868 // definition, and the function body itself must be a compound
2869 // statement.
2870 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002871 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002872}
2873
2874TEST(HasAnySubstatement, IsNotRecursive) {
2875 // It's really "has any immediate substatement".
2876 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002877 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002878}
2879
2880TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2881 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002882 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002883}
2884
2885TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2886 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002887 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002888}
2889
2890TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2891 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002892 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002893 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002894 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002895}
2896
2897TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2898 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002899 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002900 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002901 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002902 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002903 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002904}
2905
2906TEST(StatementCountIs, WorksWithMultipleStatements) {
2907 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002908 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002909}
2910
2911TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2912 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002913 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002914 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002915 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002916 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002917 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002918 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002919 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002920}
2921
2922TEST(Member, WorksInSimplestCase) {
2923 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002924 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002925}
2926
2927TEST(Member, DoesNotMatchTheBaseExpression) {
2928 // Don't pick out the wrong part of the member expression, this should
2929 // be checking the member (name) only.
2930 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002931 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002932}
2933
2934TEST(Member, MatchesInMemberFunctionCall) {
2935 EXPECT_TRUE(matches("void f() {"
2936 " struct { void first() {}; } s;"
2937 " s.first();"
2938 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002939 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002940}
2941
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002942TEST(Member, MatchesMember) {
2943 EXPECT_TRUE(matches(
2944 "struct A { int i; }; void f() { A a; a.i = 2; }",
2945 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2946 EXPECT_TRUE(notMatches(
2947 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2948 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2949}
2950
Daniel Jasper639522c2013-02-25 12:02:08 +00002951TEST(Member, UnderstandsAccess) {
2952 EXPECT_TRUE(matches(
2953 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2954 EXPECT_TRUE(notMatches(
2955 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2956 EXPECT_TRUE(notMatches(
2957 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2958
2959 EXPECT_TRUE(notMatches(
2960 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2961 EXPECT_TRUE(notMatches(
2962 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2963 EXPECT_TRUE(matches(
2964 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2965
2966 EXPECT_TRUE(notMatches(
2967 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2968 EXPECT_TRUE(matches("class A { protected: int i; };",
2969 fieldDecl(isProtected(), hasName("i"))));
2970 EXPECT_TRUE(notMatches(
2971 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2972
2973 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2974 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2975 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2976 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2977}
2978
Dmitri Gribenko06963042012-08-18 00:29:27 +00002979TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002980 // Fails in C++11 mode
2981 EXPECT_TRUE(matchesConditionally(
2982 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2983 "class X { void *operator new(std::size_t); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002984 cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002985
2986 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002987 cxxMethodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002988
Daniel Jasper5901e472012-10-01 13:40:41 +00002989 // Fails in C++11 mode
2990 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002991 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2992 "class X { void operator delete[](void*, std::size_t); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002993 cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002994}
2995
Manuel Klimek04616e42012-07-06 05:48:52 +00002996TEST(HasObjectExpression, DoesNotMatchMember) {
2997 EXPECT_TRUE(notMatches(
2998 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002999 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003000}
3001
3002TEST(HasObjectExpression, MatchesBaseOfVariable) {
3003 EXPECT_TRUE(matches(
3004 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003005 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003006 EXPECT_TRUE(matches(
3007 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003008 memberExpr(hasObjectExpression(
3009 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003010}
3011
3012TEST(HasObjectExpression,
3013 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
3014 EXPECT_TRUE(matches(
3015 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003016 memberExpr(hasObjectExpression(
3017 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003018 EXPECT_TRUE(matches(
3019 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003020 memberExpr(hasObjectExpression(
3021 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003022}
3023
3024TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003025 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
3026 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
3027 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
3028 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003029}
3030
3031TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003032 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003033}
3034
Aaron Ballman6290fc92015-11-23 17:09:24 +00003035TEST(IsVolatileQualified, QualifiersMatch) {
3036 EXPECT_TRUE(matches("volatile int i = 42;",
3037 varDecl(hasType(isVolatileQualified()))));
3038 EXPECT_TRUE(notMatches("volatile int *i;",
3039 varDecl(hasType(isVolatileQualified()))));
3040 EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
3041 varDecl(hasType(isVolatileQualified()))));
3042}
3043
Manuel Klimek04616e42012-07-06 05:48:52 +00003044TEST(IsConstQualified, MatchesConstInt) {
3045 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003046 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003047}
3048
3049TEST(IsConstQualified, MatchesConstPointer) {
3050 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003051 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003052}
3053
3054TEST(IsConstQualified, MatchesThroughTypedef) {
3055 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003056 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003057 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003058 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003059}
3060
3061TEST(IsConstQualified, DoesNotMatchInappropriately) {
3062 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003063 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003064 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003065 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003066}
3067
Sam Panzer80c13772012-08-16 16:58:10 +00003068TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003069 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
3070 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
3071 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
3072 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003073}
3074TEST(CastExpression, MatchesImplicitCasts) {
3075 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00003076 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003077 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00003078 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003079}
3080
3081TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003082 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
3083 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
3084 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
3085 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003086}
3087
Manuel Klimek04616e42012-07-06 05:48:52 +00003088TEST(ReinterpretCast, MatchesSimpleCase) {
3089 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003090 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003091}
3092
3093TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003094 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003095 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003096 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003097 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003098 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003099 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3100 "B b;"
3101 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003102 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003103}
3104
3105TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003106 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003107 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003108 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003109}
3110
3111TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003112 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003113 EXPECT_TRUE(
3114 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003115 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003116 EXPECT_TRUE(
3117 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003118 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003119}
3120
3121TEST(DynamicCast, MatchesSimpleCase) {
3122 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
3123 "B b;"
3124 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003125 cxxDynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003126}
3127
3128TEST(StaticCast, MatchesSimpleCase) {
3129 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Aaron Ballman512fb642015-09-17 13:30:52 +00003130 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003131}
3132
3133TEST(StaticCast, DoesNotMatchOtherCasts) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003134 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003135 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003136 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003137 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003138 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003139 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3140 "B b;"
3141 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003142 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003143}
3144
Daniel Jasper417f7762012-09-18 13:36:17 +00003145TEST(CStyleCast, MatchesSimpleCase) {
3146 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
3147}
3148
3149TEST(CStyleCast, DoesNotMatchOtherCasts) {
3150 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
3151 "char q, *r = const_cast<char*>(&q);"
3152 "void* s = reinterpret_cast<char*>(&s);"
3153 "struct B { virtual ~B() {} }; struct D : B {};"
3154 "B b;"
3155 "D* t = dynamic_cast<D*>(&b);",
3156 cStyleCastExpr()));
3157}
3158
Manuel Klimek04616e42012-07-06 05:48:52 +00003159TEST(HasDestinationType, MatchesSimpleCase) {
3160 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003161 cxxStaticCastExpr(hasDestinationType(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003162 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003163}
3164
Sam Panzer80c13772012-08-16 16:58:10 +00003165TEST(HasImplicitDestinationType, MatchesSimpleCase) {
3166 // This test creates an implicit const cast.
3167 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003168 implicitCastExpr(
3169 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003170 // This test creates an implicit array-to-pointer cast.
3171 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003172 implicitCastExpr(hasImplicitDestinationType(
3173 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003174}
3175
3176TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
3177 // This test creates an implicit cast from int to char.
3178 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003179 implicitCastExpr(hasImplicitDestinationType(
3180 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003181 // This test creates an implicit array-to-pointer cast.
3182 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003183 implicitCastExpr(hasImplicitDestinationType(
3184 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003185}
3186
3187TEST(ImplicitCast, MatchesSimpleCase) {
3188 // This test creates an implicit const cast.
3189 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003190 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003191 // This test creates an implicit cast from int to char.
3192 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003193 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003194 // This test creates an implicit array-to-pointer cast.
3195 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003196 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003197}
3198
3199TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003200 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00003201 // are present, and that it ignores explicit and paren casts.
3202
3203 // These two test cases have no casts.
3204 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003205 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003206 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003207 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003208
3209 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003210 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003211 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003212 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003213
3214 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003215 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003216}
3217
3218TEST(IgnoringImpCasts, MatchesImpCasts) {
3219 // This test checks that ignoringImpCasts matches when implicit casts are
3220 // present and its inner matcher alone does not match.
3221 // Note that this test creates an implicit const cast.
3222 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003223 varDecl(hasInitializer(ignoringImpCasts(
3224 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003225 // This test creates an implict cast from int to char.
3226 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003227 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003228 integerLiteral(equals(0)))))));
3229}
3230
3231TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3232 // These tests verify that ignoringImpCasts does not match if the inner
3233 // matcher does not match.
3234 // Note that the first test creates an implicit const cast.
3235 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003236 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003237 unless(anything()))))));
3238 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003239 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003240 unless(anything()))))));
3241
3242 // These tests verify that ignoringImplictCasts does not look through explicit
3243 // casts or parentheses.
3244 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003245 varDecl(hasInitializer(ignoringImpCasts(
3246 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003247 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003248 varDecl(hasInitializer(ignoringImpCasts(
3249 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003250 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003251 varDecl(hasInitializer(ignoringImpCasts(
3252 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003253 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003254 varDecl(hasInitializer(ignoringImpCasts(
3255 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003256}
3257
3258TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3259 // This test verifies that expressions that do not have implicit casts
3260 // still match the inner matcher.
3261 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003262 varDecl(hasInitializer(ignoringImpCasts(
3263 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003264}
3265
3266TEST(IgnoringParenCasts, MatchesParenCasts) {
3267 // This test checks that ignoringParenCasts matches when parentheses and/or
3268 // casts are present and its inner matcher alone does not match.
3269 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003270 varDecl(hasInitializer(ignoringParenCasts(
3271 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003272 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003273 varDecl(hasInitializer(ignoringParenCasts(
3274 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003275
3276 // This test creates an implict cast from int to char in addition to the
3277 // parentheses.
3278 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003279 varDecl(hasInitializer(ignoringParenCasts(
3280 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003281
3282 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003283 varDecl(hasInitializer(ignoringParenCasts(
3284 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003285 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003286 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003287 integerLiteral(equals(0)))))));
3288}
3289
3290TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3291 // This test verifies that expressions that do not have any casts still match.
3292 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003293 varDecl(hasInitializer(ignoringParenCasts(
3294 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003295}
3296
3297TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3298 // These tests verify that ignoringImpCasts does not match if the inner
3299 // matcher does not match.
3300 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003301 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003302 unless(anything()))))));
3303
3304 // This test creates an implicit cast from int to char in addition to the
3305 // parentheses.
3306 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003307 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003308 unless(anything()))))));
3309
3310 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003311 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003312 unless(anything()))))));
3313}
3314
3315TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3316 // This test checks that ignoringParenAndImpCasts matches when
3317 // parentheses and/or implicit casts are present and its inner matcher alone
3318 // does not match.
3319 // Note that this test creates an implicit const cast.
3320 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003321 varDecl(hasInitializer(ignoringParenImpCasts(
3322 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003323 // This test creates an implicit cast from int to char.
3324 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003325 varDecl(hasInitializer(ignoringParenImpCasts(
3326 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003327}
3328
3329TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3330 // This test verifies that expressions that do not have parentheses or
3331 // implicit casts still match.
3332 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003333 varDecl(hasInitializer(ignoringParenImpCasts(
3334 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003335 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003336 varDecl(hasInitializer(ignoringParenImpCasts(
3337 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003338}
3339
3340TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3341 // These tests verify that ignoringParenImpCasts does not match if
3342 // the inner matcher does not match.
3343 // This test creates an implicit cast.
3344 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003345 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003346 unless(anything()))))));
3347 // These tests verify that ignoringParenAndImplictCasts does not look
3348 // through explicit casts.
3349 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003350 varDecl(hasInitializer(ignoringParenImpCasts(
3351 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003352 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003353 varDecl(hasInitializer(ignoringParenImpCasts(
3354 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003355 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003356 varDecl(hasInitializer(ignoringParenImpCasts(
3357 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003358}
3359
Manuel Klimeke9235692012-07-25 10:02:02 +00003360TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003361 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3362 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003363 implicitCastExpr(
Aaron Ballman512fb642015-09-17 13:30:52 +00003364 hasSourceExpression(cxxConstructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003365}
3366
Manuel Klimeke9235692012-07-25 10:02:02 +00003367TEST(HasSourceExpression, MatchesExplicitCasts) {
3368 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003369 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003370 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003371 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003372}
3373
Manuel Klimek04616e42012-07-06 05:48:52 +00003374TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003375 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003376}
3377
3378TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003379 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003380}
3381
3382TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003383 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003384}
3385
3386TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003387 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003388}
3389
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003390TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3391 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3392 "const Foo f = Foo();",
3393 varDecl(hasInitializer(exprWithCleanups()))));
3394 EXPECT_FALSE(matches("struct Foo { };"
3395 "const Foo f = Foo();",
3396 varDecl(hasInitializer(exprWithCleanups()))));
3397}
3398
Daniel Jasper1dad1832012-07-10 20:20:19 +00003399TEST(InitListExpression, MatchesInitListExpression) {
3400 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3401 initListExpr(hasType(asString("int [2]")))));
3402 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003403 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003404 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3405 "void f();"
3406 "S s[1] = { &f };",
3407 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003408 EXPECT_TRUE(
3409 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003410}
3411
3412TEST(UsingDeclaration, MatchesUsingDeclarations) {
3413 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3414 usingDecl()));
3415}
3416
3417TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3418 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3419 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3420}
3421
3422TEST(UsingDeclaration, MatchesSpecificTarget) {
3423 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3424 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003425 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003426 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3427 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003428 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003429}
3430
3431TEST(UsingDeclaration, ThroughUsingDeclaration) {
3432 EXPECT_TRUE(matches(
3433 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003434 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003435 EXPECT_TRUE(notMatches(
3436 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003437 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003438}
3439
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003440TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3441 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3442 usingDirectiveDecl()));
3443 EXPECT_FALSE(
3444 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3445}
3446
Sam Panzerd624bfb2012-08-16 17:20:59 +00003447TEST(SingleDecl, IsSingleDecl) {
3448 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003449 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003450 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3451 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3452 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3453 SingleDeclStmt));
3454}
3455
3456TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003457 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003458
3459 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003460 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003461 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003462 declStmt(containsDeclaration(0, MatchesInit),
3463 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003464 unsigned WrongIndex = 42;
3465 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003466 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003467 MatchesInit))));
3468}
3469
3470TEST(DeclCount, DeclCountIsCorrect) {
3471 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003472 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003473 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003474 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003475 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003476 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003477}
3478
Manuel Klimek04616e42012-07-06 05:48:52 +00003479TEST(While, MatchesWhileLoops) {
3480 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3481 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3482 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3483}
3484
3485TEST(Do, MatchesDoLoops) {
3486 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3487 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3488}
3489
3490TEST(Do, DoesNotMatchWhileLoops) {
3491 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3492}
3493
3494TEST(SwitchCase, MatchesCase) {
3495 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3496 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3497 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3498 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3499}
3500
Daniel Jasper87c3d362012-09-20 14:12:57 +00003501TEST(SwitchCase, MatchesSwitch) {
3502 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3503 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3504 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3505 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3506}
3507
Peter Collingbourne3154a102013-05-10 11:52:02 +00003508TEST(SwitchCase, MatchesEachCase) {
3509 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3510 switchStmt(forEachSwitchCase(caseStmt()))));
3511 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3512 switchStmt(forEachSwitchCase(caseStmt()))));
3513 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3514 switchStmt(forEachSwitchCase(caseStmt()))));
3515 EXPECT_TRUE(notMatches(
3516 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3517 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3518 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3519 switchStmt(forEachSwitchCase(
3520 caseStmt(hasCaseConstant(integerLiteral()))))));
3521 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3522 switchStmt(forEachSwitchCase(
3523 caseStmt(hasCaseConstant(integerLiteral()))))));
3524 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3525 switchStmt(forEachSwitchCase(
3526 caseStmt(hasCaseConstant(integerLiteral()))))));
3527 EXPECT_TRUE(matchAndVerifyResultTrue(
3528 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3529 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3530 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3531}
3532
Manuel Klimekba46fc02013-07-19 11:50:54 +00003533TEST(ForEachConstructorInitializer, MatchesInitializers) {
3534 EXPECT_TRUE(matches(
3535 "struct X { X() : i(42), j(42) {} int i, j; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003536 cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer()))));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003537}
3538
Daniel Jasper87c3d362012-09-20 14:12:57 +00003539TEST(ExceptionHandling, SimpleCases) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003540 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
3541 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
3542 EXPECT_TRUE(
3543 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003544 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003545 cxxThrowExpr()));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003546 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003547 cxxThrowExpr()));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003548 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003549 cxxCatchStmt(isCatchAll())));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003550 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003551 cxxCatchStmt(isCatchAll())));
Aaron Ballman39918462015-07-15 17:11:21 +00003552 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3553 varDecl(isExceptionVariable())));
3554 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3555 varDecl(isExceptionVariable())));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003556}
3557
Manuel Klimek04616e42012-07-06 05:48:52 +00003558TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3559 EXPECT_TRUE(notMatches(
3560 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003561 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003562 EXPECT_TRUE(notMatches(
3563 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003564 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003565}
3566
3567TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3568 EXPECT_TRUE(matches(
3569 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003570 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003571}
3572
3573TEST(ForEach, BindsOneNode) {
3574 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003575 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003576 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003577}
3578
3579TEST(ForEach, BindsMultipleNodes) {
3580 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003581 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003582 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003583}
3584
3585TEST(ForEach, BindsRecursiveCombinations) {
3586 EXPECT_TRUE(matchAndVerifyResultTrue(
3587 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003588 recordDecl(hasName("C"),
3589 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003590 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003591}
3592
3593TEST(ForEachDescendant, BindsOneNode) {
3594 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003595 recordDecl(hasName("C"),
3596 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003597 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003598}
3599
Daniel Jasper94a56852012-11-16 18:39:22 +00003600TEST(ForEachDescendant, NestedForEachDescendant) {
3601 DeclarationMatcher m = recordDecl(
3602 isDefinition(), decl().bind("x"), hasName("C"));
3603 EXPECT_TRUE(matchAndVerifyResultTrue(
3604 "class A { class B { class C {}; }; };",
3605 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3606 new VerifyIdIsBoundTo<Decl>("x", "C")));
3607
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003608 // Check that a partial match of 'm' that binds 'x' in the
3609 // first part of anyOf(m, anything()) will not overwrite the
3610 // binding created by the earlier binding in the hasDescendant.
3611 EXPECT_TRUE(matchAndVerifyResultTrue(
3612 "class A { class B { class C {}; }; };",
3613 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3614 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003615}
3616
Manuel Klimek04616e42012-07-06 05:48:52 +00003617TEST(ForEachDescendant, BindsMultipleNodes) {
3618 EXPECT_TRUE(matchAndVerifyResultTrue(
3619 "class C { class D { int x; int y; }; "
3620 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003621 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003622 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003623}
3624
3625TEST(ForEachDescendant, BindsRecursiveCombinations) {
3626 EXPECT_TRUE(matchAndVerifyResultTrue(
3627 "class C { class D { "
3628 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003629 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3630 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003631 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003632}
3633
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003634TEST(ForEachDescendant, BindsCombinations) {
3635 EXPECT_TRUE(matchAndVerifyResultTrue(
3636 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3637 "(true) {} }",
3638 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3639 forEachDescendant(whileStmt().bind("while"))),
3640 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3641}
3642
3643TEST(Has, DoesNotDeleteBindings) {
3644 EXPECT_TRUE(matchAndVerifyResultTrue(
3645 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3646 new VerifyIdIsBoundTo<Decl>("x", 1)));
3647}
3648
3649TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3650 // Those matchers cover all the cases where an inner matcher is called
3651 // and there is not a 1:1 relationship between the match of the outer
3652 // matcher and the match of the inner matcher.
3653 // The pattern to look for is:
3654 // ... return InnerMatcher.matches(...); ...
3655 // In which case no special handling is needed.
3656 //
3657 // On the other hand, if there are multiple alternative matches
3658 // (for example forEach*) or matches might be discarded (for example has*)
3659 // the implementation must make sure that the discarded matches do not
3660 // affect the bindings.
3661 // When new such matchers are added, add a test here that:
3662 // - matches a simple node, and binds it as the first thing in the matcher:
3663 // recordDecl(decl().bind("x"), hasName("X")))
3664 // - uses the matcher under test afterwards in a way that not the first
3665 // alternative is matched; for anyOf, that means the first branch
3666 // would need to return false; for hasAncestor, it means that not
3667 // the direct parent matches the inner matcher.
3668
3669 EXPECT_TRUE(matchAndVerifyResultTrue(
3670 "class X { int y; };",
3671 recordDecl(
3672 recordDecl().bind("x"), hasName("::X"),
3673 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3674 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3675 EXPECT_TRUE(matchAndVerifyResultTrue(
3676 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3677 anyOf(unless(anything()), anything())),
3678 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3679 EXPECT_TRUE(matchAndVerifyResultTrue(
3680 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3681 classTemplateSpecializationDecl(
3682 decl().bind("x"),
3683 hasAnyTemplateArgument(refersToType(asString("int")))),
3684 new VerifyIdIsBoundTo<Decl>("x", 1)));
3685 EXPECT_TRUE(matchAndVerifyResultTrue(
3686 "class X { void f(); void g(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003687 cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003688 new VerifyIdIsBoundTo<Decl>("x", 1)));
3689 EXPECT_TRUE(matchAndVerifyResultTrue(
3690 "class X { X() : a(1), b(2) {} double a; int b; };",
3691 recordDecl(decl().bind("x"),
Aaron Ballman512fb642015-09-17 13:30:52 +00003692 has(cxxConstructorDecl(
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003693 hasAnyConstructorInitializer(forField(hasName("b")))))),
3694 new VerifyIdIsBoundTo<Decl>("x", 1)));
3695 EXPECT_TRUE(matchAndVerifyResultTrue(
3696 "void x(int, int) { x(0, 42); }",
3697 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3698 new VerifyIdIsBoundTo<Expr>("x", 1)));
3699 EXPECT_TRUE(matchAndVerifyResultTrue(
3700 "void x(int, int y) {}",
3701 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3702 new VerifyIdIsBoundTo<Decl>("x", 1)));
3703 EXPECT_TRUE(matchAndVerifyResultTrue(
3704 "void x() { return; if (true) {} }",
3705 functionDecl(decl().bind("x"),
3706 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3707 new VerifyIdIsBoundTo<Decl>("x", 1)));
3708 EXPECT_TRUE(matchAndVerifyResultTrue(
3709 "namespace X { void b(int); void b(); }"
3710 "using X::b;",
3711 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3712 functionDecl(parameterCountIs(1))))),
3713 new VerifyIdIsBoundTo<Decl>("x", 1)));
3714 EXPECT_TRUE(matchAndVerifyResultTrue(
3715 "class A{}; class B{}; class C : B, A {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003716 cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003717 new VerifyIdIsBoundTo<Decl>("x", 1)));
3718 EXPECT_TRUE(matchAndVerifyResultTrue(
3719 "class A{}; typedef A B; typedef A C; typedef A D;"
3720 "class E : A {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003721 cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003722 new VerifyIdIsBoundTo<Decl>("x", 1)));
3723 EXPECT_TRUE(matchAndVerifyResultTrue(
3724 "class A { class B { void f() {} }; };",
3725 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3726 new VerifyIdIsBoundTo<Decl>("x", 1)));
3727 EXPECT_TRUE(matchAndVerifyResultTrue(
3728 "template <typename T> struct A { struct B {"
3729 " void f() { if(true) {} }"
3730 "}; };"
3731 "void t() { A<int>::B b; b.f(); }",
3732 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3733 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3734 EXPECT_TRUE(matchAndVerifyResultTrue(
3735 "class A {};",
3736 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3737 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003738 EXPECT_TRUE(matchAndVerifyResultTrue(
3739 "class A { A() : s(), i(42) {} const char *s; int i; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003740 cxxConstructorDecl(hasName("::A::A"), decl().bind("x"),
3741 forEachConstructorInitializer(forField(hasName("i")))),
Manuel Klimekba46fc02013-07-19 11:50:54 +00003742 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003743}
3744
Daniel Jasper33806cd2012-11-11 22:14:55 +00003745TEST(ForEachDescendant, BindsCorrectNodes) {
3746 EXPECT_TRUE(matchAndVerifyResultTrue(
3747 "class C { void f(); int i; };",
3748 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3749 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3750 EXPECT_TRUE(matchAndVerifyResultTrue(
3751 "class C { void f() {} int i; };",
3752 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3753 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3754}
3755
Manuel Klimekabf43712013-02-04 10:59:20 +00003756TEST(FindAll, BindsNodeOnMatch) {
3757 EXPECT_TRUE(matchAndVerifyResultTrue(
3758 "class A {};",
3759 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3760 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3761}
3762
3763TEST(FindAll, BindsDescendantNodeOnMatch) {
3764 EXPECT_TRUE(matchAndVerifyResultTrue(
3765 "class A { int a; int b; };",
3766 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3767 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3768}
3769
3770TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3771 EXPECT_TRUE(matchAndVerifyResultTrue(
3772 "class A { int a; int b; };",
3773 recordDecl(hasName("::A"),
3774 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3775 fieldDecl().bind("v"))))),
3776 new VerifyIdIsBoundTo<Decl>("v", 3)));
3777
3778 EXPECT_TRUE(matchAndVerifyResultTrue(
3779 "class A { class B {}; class C {}; };",
3780 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3781 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3782}
3783
Manuel Klimek88b95872013-02-04 09:42:38 +00003784TEST(EachOf, TriggersForEachMatch) {
3785 EXPECT_TRUE(matchAndVerifyResultTrue(
3786 "class A { int a; int b; };",
3787 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3788 has(fieldDecl(hasName("b")).bind("v")))),
3789 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3790}
3791
3792TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3793 EXPECT_TRUE(matchAndVerifyResultTrue(
3794 "class A { int a; int c; };",
3795 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3796 has(fieldDecl(hasName("b")).bind("v")))),
3797 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3798 EXPECT_TRUE(matchAndVerifyResultTrue(
3799 "class A { int c; int b; };",
3800 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3801 has(fieldDecl(hasName("b")).bind("v")))),
3802 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3803 EXPECT_TRUE(notMatches(
3804 "class A { int c; int d; };",
3805 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3806 has(fieldDecl(hasName("b")).bind("v"))))));
3807}
Manuel Klimek04616e42012-07-06 05:48:52 +00003808
3809TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3810 // Make sure that we can both match the class by name (::X) and by the type
3811 // the template was instantiated with (via a field).
3812
3813 EXPECT_TRUE(matches(
3814 "template <typename T> class X {}; class A {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003815 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003816
3817 EXPECT_TRUE(matches(
3818 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003819 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003820 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003821}
3822
3823TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3824 EXPECT_TRUE(matches(
3825 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003826 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003827 isTemplateInstantiation())));
3828}
3829
3830TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3831 EXPECT_TRUE(matches(
3832 "template <typename T> class X { T t; }; class A {};"
3833 "template class X<A>;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003834 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003835 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003836}
3837
3838TEST(IsTemplateInstantiation,
3839 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3840 EXPECT_TRUE(matches(
3841 "template <typename T> class X {};"
3842 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003843 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003844}
3845
3846TEST(IsTemplateInstantiation,
3847 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3848 EXPECT_TRUE(matches(
3849 "class A {};"
3850 "class X {"
3851 " template <typename U> class Y { U u; };"
3852 " Y<A> y;"
3853 "};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003854 cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003855}
3856
3857TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3858 // FIXME: Figure out whether this makes sense. It doesn't affect the
3859 // normal use case as long as the uppermost instantiation always is marked
3860 // as template instantiation, but it might be confusing as a predicate.
3861 EXPECT_TRUE(matches(
3862 "class A {};"
3863 "template <typename T> class X {"
3864 " template <typename U> class Y { U u; };"
3865 " Y<T> y;"
3866 "}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003867 cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003868}
3869
3870TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3871 EXPECT_TRUE(notMatches(
3872 "template <typename T> class X {}; class A {};"
3873 "template <> class X<A> {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003874 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003875}
3876
3877TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3878 EXPECT_TRUE(notMatches(
3879 "class A {}; class Y { A a; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003880 cxxRecordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003881}
3882
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003883TEST(IsInstantiated, MatchesInstantiation) {
3884 EXPECT_TRUE(
3885 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003886 cxxRecordDecl(isInstantiated())));
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003887}
3888
3889TEST(IsInstantiated, NotMatchesDefinition) {
3890 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003891 cxxRecordDecl(isInstantiated())));
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003892}
3893
3894TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3895 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3896 "class Y { A<int> a; }; Y y;",
3897 declStmt(isInTemplateInstantiation())));
3898}
3899
3900TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3901 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3902 declStmt(isInTemplateInstantiation())));
3903}
3904
3905TEST(IsInstantiated, MatchesFunctionInstantiation) {
3906 EXPECT_TRUE(
3907 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3908 functionDecl(isInstantiated())));
3909}
3910
3911TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3912 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3913 varDecl(isInstantiated())));
3914}
3915
3916TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3917 EXPECT_TRUE(
3918 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3919 declStmt(isInTemplateInstantiation())));
3920}
3921
3922TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3923 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3924 declStmt(isInTemplateInstantiation())));
3925}
3926
3927TEST(IsInTemplateInstantiation, Sharing) {
3928 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3929 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3930 // and makes the matcher behave in non-obvious ways.
3931 EXPECT_TRUE(notMatches(
3932 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3933 Matcher));
3934 EXPECT_TRUE(matches(
3935 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3936 Matcher));
3937}
3938
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003939TEST(IsExplicitTemplateSpecialization,
3940 DoesNotMatchPrimaryTemplate) {
3941 EXPECT_TRUE(notMatches(
3942 "template <typename T> class X {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003943 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003944 EXPECT_TRUE(notMatches(
3945 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003946 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003947}
3948
3949TEST(IsExplicitTemplateSpecialization,
3950 DoesNotMatchExplicitTemplateInstantiations) {
3951 EXPECT_TRUE(notMatches(
3952 "template <typename T> class X {};"
3953 "template class X<int>; extern template class X<long>;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003954 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003955 EXPECT_TRUE(notMatches(
3956 "template <typename T> void f(T t) {}"
3957 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003958 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003959}
3960
3961TEST(IsExplicitTemplateSpecialization,
3962 DoesNotMatchImplicitTemplateInstantiations) {
3963 EXPECT_TRUE(notMatches(
3964 "template <typename T> class X {}; X<int> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003965 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003966 EXPECT_TRUE(notMatches(
3967 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003968 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003969}
3970
3971TEST(IsExplicitTemplateSpecialization,
3972 MatchesExplicitTemplateSpecializations) {
3973 EXPECT_TRUE(matches(
3974 "template <typename T> class X {};"
3975 "template<> class X<int> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003976 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003977 EXPECT_TRUE(matches(
3978 "template <typename T> void f(T t) {}"
3979 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003980 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003981}
3982
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003983TEST(HasAncenstor, MatchesDeclarationAncestors) {
3984 EXPECT_TRUE(matches(
3985 "class A { class B { class C {}; }; };",
3986 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3987}
3988
3989TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3990 EXPECT_TRUE(notMatches(
3991 "class A { class B { class C {}; }; };",
3992 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3993}
3994
3995TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3996 EXPECT_TRUE(matches(
3997 "class A { class B { void f() { C c; } class C {}; }; };",
3998 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3999 hasAncestor(recordDecl(hasName("A"))))))));
4000}
4001
4002TEST(HasAncenstor, MatchesStatementAncestors) {
4003 EXPECT_TRUE(matches(
4004 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00004005 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004006}
4007
4008TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
4009 EXPECT_TRUE(matches(
4010 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00004011 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004012}
4013
4014TEST(HasAncestor, BindsRecursiveCombinations) {
4015 EXPECT_TRUE(matchAndVerifyResultTrue(
4016 "class C { class D { class E { class F { int y; }; }; }; };",
4017 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004018 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004019}
4020
4021TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
4022 EXPECT_TRUE(matchAndVerifyResultTrue(
4023 "class C { class D { class E { class F { int y; }; }; }; };",
4024 fieldDecl(hasAncestor(
4025 decl(
4026 hasDescendant(recordDecl(isDefinition(),
4027 hasAncestor(recordDecl())))
4028 ).bind("d")
4029 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004030 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004031}
4032
Manuel Klimekb64d6b72013-03-14 16:33:21 +00004033TEST(HasAncestor, MatchesClosestAncestor) {
4034 EXPECT_TRUE(matchAndVerifyResultTrue(
4035 "template <typename T> struct C {"
4036 " void f(int) {"
4037 " struct I { void g(T) { int x; } } i; i.g(42);"
4038 " }"
4039 "};"
4040 "template struct C<int>;",
4041 varDecl(hasName("x"),
4042 hasAncestor(functionDecl(hasParameter(
4043 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
4044 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
4045}
4046
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004047TEST(HasAncestor, MatchesInTemplateInstantiations) {
4048 EXPECT_TRUE(matches(
4049 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
4050 "A<int>::B::C a;",
4051 fieldDecl(hasType(asString("int")),
4052 hasAncestor(recordDecl(hasName("A"))))));
4053}
4054
4055TEST(HasAncestor, MatchesInImplicitCode) {
4056 EXPECT_TRUE(matches(
4057 "struct X {}; struct A { A() {} X x; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00004058 cxxConstructorDecl(
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004059 hasAnyConstructorInitializer(withInitializer(expr(
4060 hasAncestor(recordDecl(hasName("A")))))))));
4061}
4062
Daniel Jasper632aea92012-10-22 16:26:51 +00004063TEST(HasParent, MatchesOnlyParent) {
4064 EXPECT_TRUE(matches(
4065 "void f() { if (true) { int x = 42; } }",
4066 compoundStmt(hasParent(ifStmt()))));
4067 EXPECT_TRUE(notMatches(
4068 "void f() { for (;;) { int x = 42; } }",
4069 compoundStmt(hasParent(ifStmt()))));
4070 EXPECT_TRUE(notMatches(
4071 "void f() { if (true) for (;;) { int x = 42; } }",
4072 compoundStmt(hasParent(ifStmt()))));
4073}
4074
Manuel Klimekc844a462012-12-06 14:42:48 +00004075TEST(HasAncestor, MatchesAllAncestors) {
4076 EXPECT_TRUE(matches(
4077 "template <typename T> struct C { static void f() { 42; } };"
4078 "void t() { C<int>::f(); }",
4079 integerLiteral(
4080 equals(42),
Aaron Ballman512fb642015-09-17 13:30:52 +00004081 allOf(
4082 hasAncestor(cxxRecordDecl(isTemplateInstantiation())),
4083 hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation())))))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004084}
4085
4086TEST(HasParent, MatchesAllParents) {
4087 EXPECT_TRUE(matches(
4088 "template <typename T> struct C { static void f() { 42; } };"
4089 "void t() { C<int>::f(); }",
4090 integerLiteral(
4091 equals(42),
4092 hasParent(compoundStmt(hasParent(functionDecl(
Aaron Ballman512fb642015-09-17 13:30:52 +00004093 hasParent(cxxRecordDecl(isTemplateInstantiation())))))))));
4094 EXPECT_TRUE(
4095 matches("template <typename T> struct C { static void f() { 42; } };"
4096 "void t() { C<int>::f(); }",
4097 integerLiteral(
4098 equals(42),
4099 hasParent(compoundStmt(hasParent(functionDecl(hasParent(
4100 cxxRecordDecl(unless(isTemplateInstantiation()))))))))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004101 EXPECT_TRUE(matches(
4102 "template <typename T> struct C { static void f() { 42; } };"
4103 "void t() { C<int>::f(); }",
4104 integerLiteral(equals(42),
Aaron Ballman512fb642015-09-17 13:30:52 +00004105 hasParent(compoundStmt(
4106 allOf(hasParent(functionDecl(hasParent(
4107 cxxRecordDecl(isTemplateInstantiation())))),
4108 hasParent(functionDecl(hasParent(cxxRecordDecl(
4109 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00004110 EXPECT_TRUE(
4111 notMatches("template <typename T> struct C { static void f() {} };"
4112 "void t() { C<int>::f(); }",
4113 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004114}
4115
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00004116TEST(HasParent, NoDuplicateParents) {
4117 class HasDuplicateParents : public BoundNodesCallback {
4118 public:
4119 bool run(const BoundNodes *Nodes) override { return false; }
4120 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
4121 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
4122 std::set<const void *> Parents;
4123 for (const auto &Parent : Context->getParents(*Node)) {
4124 if (!Parents.insert(Parent.getMemoizationData()).second) {
4125 return true;
4126 }
4127 }
4128 return false;
4129 }
4130 };
4131 EXPECT_FALSE(matchAndVerifyResultTrue(
4132 "template <typename T> int Foo() { return 1 + 2; }\n"
4133 "int x = Foo<int>() + Foo<unsigned>();",
4134 stmt().bind("node"), new HasDuplicateParents()));
4135}
4136
Daniel Jasper516b02e2012-10-17 08:52:59 +00004137TEST(TypeMatching, MatchesTypes) {
4138 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
4139}
4140
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004141TEST(TypeMatching, MatchesVoid) {
Aaron Ballman512fb642015-09-17 13:30:52 +00004142 EXPECT_TRUE(matches("struct S { void func(); };",
4143 cxxMethodDecl(returns(voidType()))));
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004144}
4145
Daniel Jasper516b02e2012-10-17 08:52:59 +00004146TEST(TypeMatching, MatchesArrayTypes) {
4147 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
4148 EXPECT_TRUE(matches("int a[42];", arrayType()));
4149 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
4150
4151 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
4152 arrayType(hasElementType(builtinType()))));
4153
4154 EXPECT_TRUE(matches(
4155 "int const a[] = { 2, 3 };",
4156 qualType(arrayType(hasElementType(builtinType())))));
4157 EXPECT_TRUE(matches(
4158 "int const a[] = { 2, 3 };",
4159 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4160 EXPECT_TRUE(matches(
4161 "typedef const int T; T x[] = { 1, 2 };",
4162 qualType(isConstQualified(), arrayType())));
4163
4164 EXPECT_TRUE(notMatches(
4165 "int a[] = { 2, 3 };",
4166 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4167 EXPECT_TRUE(notMatches(
4168 "int a[] = { 2, 3 };",
4169 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
4170 EXPECT_TRUE(notMatches(
4171 "int const a[] = { 2, 3 };",
4172 qualType(arrayType(hasElementType(builtinType())),
4173 unless(isConstQualified()))));
4174
4175 EXPECT_TRUE(matches("int a[2];",
4176 constantArrayType(hasElementType(builtinType()))));
4177 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
4178}
4179
Matthias Gehre2cf7e802015-10-12 21:46:07 +00004180TEST(TypeMatching, DecayedType) {
4181 EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
4182 EXPECT_TRUE(notMatches("int i[7];", decayedType()));
4183}
4184
Daniel Jasper516b02e2012-10-17 08:52:59 +00004185TEST(TypeMatching, MatchesComplexTypes) {
4186 EXPECT_TRUE(matches("_Complex float f;", complexType()));
4187 EXPECT_TRUE(matches(
4188 "_Complex float f;",
4189 complexType(hasElementType(builtinType()))));
4190 EXPECT_TRUE(notMatches(
4191 "_Complex float f;",
4192 complexType(hasElementType(isInteger()))));
4193}
4194
4195TEST(TypeMatching, MatchesConstantArrayTypes) {
4196 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
4197 EXPECT_TRUE(notMatches(
4198 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
4199 constantArrayType(hasElementType(builtinType()))));
4200
4201 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
4202 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
4203 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
4204}
4205
4206TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
4207 EXPECT_TRUE(matches(
4208 "template <typename T, int Size> class array { T data[Size]; };",
4209 dependentSizedArrayType()));
4210 EXPECT_TRUE(notMatches(
4211 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
4212 dependentSizedArrayType()));
4213}
4214
4215TEST(TypeMatching, MatchesIncompleteArrayType) {
4216 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
4217 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
4218
4219 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
4220 incompleteArrayType()));
4221}
4222
4223TEST(TypeMatching, MatchesVariableArrayType) {
4224 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
4225 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4226
4227 EXPECT_TRUE(matches(
4228 "void f(int b) { int a[b]; }",
4229 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4230 varDecl(hasName("b")))))))));
4231}
4232
4233TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00004234 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4235 llvm::Triple::Win32) {
4236 // FIXME: Make this work for MSVC.
4237 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004238
David Majnemer197e2102014-03-05 06:32:38 +00004239 EXPECT_TRUE(matches("_Atomic(int) i;",
4240 atomicType(hasValueType(isInteger()))));
4241 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4242 atomicType(hasValueType(isInteger()))));
4243 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004244}
4245
4246TEST(TypeMatching, MatchesAutoTypes) {
4247 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4248 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4249 autoType()));
4250
Richard Smith061f1e22013-04-30 21:23:01 +00004251 // FIXME: Matching against the type-as-written can't work here, because the
4252 // type as written was not deduced.
4253 //EXPECT_TRUE(matches("auto a = 1;",
4254 // autoType(hasDeducedType(isInteger()))));
4255 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4256 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004257}
4258
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004259TEST(TypeMatching, MatchesFunctionTypes) {
4260 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4261 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4262}
4263
Edwin Vaneec074802013-04-01 18:33:34 +00004264TEST(TypeMatching, MatchesParenType) {
4265 EXPECT_TRUE(
4266 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4267 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4268
4269 EXPECT_TRUE(matches(
4270 "int (*ptr_to_func)(int);",
4271 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4272 EXPECT_TRUE(notMatches(
4273 "int (*ptr_to_array)[4];",
4274 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4275}
4276
Daniel Jasper516b02e2012-10-17 08:52:59 +00004277TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004278 // FIXME: Reactive when these tests can be more specific (not matching
4279 // implicit code on certain platforms), likely when we have hasDescendant for
4280 // Types/TypeLocs.
4281 //EXPECT_TRUE(matchAndVerifyResultTrue(
4282 // "int* a;",
4283 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4284 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4285 //EXPECT_TRUE(matchAndVerifyResultTrue(
4286 // "int* a;",
4287 // pointerTypeLoc().bind("loc"),
4288 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004289 EXPECT_TRUE(matches(
4290 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004291 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004292 EXPECT_TRUE(matches(
4293 "int** a;",
4294 loc(pointerType(pointee(pointerType())))));
4295 EXPECT_TRUE(matches(
4296 "int* b; int* * const a = &b;",
4297 loc(qualType(isConstQualified(), pointerType()))));
4298
4299 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004300 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4301 hasType(blockPointerType()))));
4302 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4303 hasType(memberPointerType()))));
4304 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4305 hasType(pointerType()))));
4306 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4307 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004308 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4309 hasType(lValueReferenceType()))));
4310 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4311 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004312
Daniel Jasper7943eb52012-10-17 13:35:36 +00004313 Fragment = "int *ptr;";
4314 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4315 hasType(blockPointerType()))));
4316 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4317 hasType(memberPointerType()))));
4318 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4319 hasType(pointerType()))));
4320 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4321 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004322
Daniel Jasper7943eb52012-10-17 13:35:36 +00004323 Fragment = "int a; int &ref = a;";
4324 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4325 hasType(blockPointerType()))));
4326 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4327 hasType(memberPointerType()))));
4328 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4329 hasType(pointerType()))));
4330 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4331 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004332 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4333 hasType(lValueReferenceType()))));
4334 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4335 hasType(rValueReferenceType()))));
4336
4337 Fragment = "int &&ref = 2;";
4338 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4339 hasType(blockPointerType()))));
4340 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4341 hasType(memberPointerType()))));
4342 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4343 hasType(pointerType()))));
4344 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4345 hasType(referenceType()))));
4346 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4347 hasType(lValueReferenceType()))));
4348 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4349 hasType(rValueReferenceType()))));
4350}
4351
4352TEST(TypeMatching, AutoRefTypes) {
4353 std::string Fragment = "auto a = 1;"
4354 "auto b = a;"
4355 "auto &c = a;"
4356 "auto &&d = c;"
4357 "auto &&e = 2;";
4358 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4359 hasType(referenceType()))));
4360 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4361 hasType(referenceType()))));
4362 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4363 hasType(referenceType()))));
4364 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4365 hasType(lValueReferenceType()))));
4366 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4367 hasType(rValueReferenceType()))));
4368 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4369 hasType(referenceType()))));
4370 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4371 hasType(lValueReferenceType()))));
4372 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4373 hasType(rValueReferenceType()))));
4374 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4375 hasType(referenceType()))));
4376 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4377 hasType(lValueReferenceType()))));
4378 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4379 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004380}
4381
4382TEST(TypeMatching, PointeeTypes) {
4383 EXPECT_TRUE(matches("int b; int &a = b;",
4384 referenceType(pointee(builtinType()))));
4385 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4386
4387 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004388 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004389
4390 EXPECT_TRUE(matches(
4391 "int const *A;",
4392 pointerType(pointee(isConstQualified(), builtinType()))));
4393 EXPECT_TRUE(notMatches(
4394 "int *A;",
4395 pointerType(pointee(isConstQualified(), builtinType()))));
4396}
4397
4398TEST(TypeMatching, MatchesPointersToConstTypes) {
4399 EXPECT_TRUE(matches("int b; int * const a = &b;",
4400 loc(pointerType())));
4401 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004402 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004403 EXPECT_TRUE(matches(
4404 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004405 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004406 EXPECT_TRUE(matches(
4407 "int b; const int * a = &b;",
4408 pointerType(pointee(builtinType()))));
4409}
4410
4411TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004412 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4413 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004414}
4415
Edwin Vanef901b712013-02-25 14:49:29 +00004416TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004417 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004418 templateSpecializationType()));
4419}
4420
Edwin Vaneb6eae142013-02-25 20:43:32 +00004421TEST(TypeMatching, MatchesRecordType) {
4422 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004423 EXPECT_TRUE(matches("struct S{}; S s;",
4424 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4425 EXPECT_TRUE(notMatches("int i;",
4426 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004427}
4428
4429TEST(TypeMatching, MatchesElaboratedType) {
4430 EXPECT_TRUE(matches(
4431 "namespace N {"
4432 " namespace M {"
4433 " class D {};"
4434 " }"
4435 "}"
4436 "N::M::D d;", elaboratedType()));
4437 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4438 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4439}
4440
4441TEST(ElaboratedTypeNarrowing, hasQualifier) {
4442 EXPECT_TRUE(matches(
4443 "namespace N {"
4444 " namespace M {"
4445 " class D {};"
4446 " }"
4447 "}"
4448 "N::M::D d;",
4449 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4450 EXPECT_TRUE(notMatches(
4451 "namespace M {"
4452 " class D {};"
4453 "}"
4454 "M::D d;",
4455 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004456 EXPECT_TRUE(notMatches(
4457 "struct D {"
4458 "} d;",
4459 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004460}
4461
4462TEST(ElaboratedTypeNarrowing, namesType) {
4463 EXPECT_TRUE(matches(
4464 "namespace N {"
4465 " namespace M {"
4466 " class D {};"
4467 " }"
4468 "}"
4469 "N::M::D d;",
4470 elaboratedType(elaboratedType(namesType(recordType(
4471 hasDeclaration(namedDecl(hasName("D")))))))));
4472 EXPECT_TRUE(notMatches(
4473 "namespace M {"
4474 " class D {};"
4475 "}"
4476 "M::D d;",
4477 elaboratedType(elaboratedType(namesType(typedefType())))));
4478}
4479
Samuel Benzaquenf8ec4542015-08-26 16:15:59 +00004480TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
4481 const std::string code = "template <typename T>"
4482 "int F() {"
4483 " return 1 + T();"
4484 "}"
4485 "int i = F<int>();";
4486 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
4487 expr(hasType(substTemplateTypeParmType()))))));
4488 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
4489 expr(hasType(substTemplateTypeParmType()))))));
4490}
4491
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004492TEST(NNS, MatchesNestedNameSpecifiers) {
4493 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4494 nestedNameSpecifier()));
4495 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4496 nestedNameSpecifier()));
4497 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4498 nestedNameSpecifier()));
Daniel Jasperc8f472c2015-12-02 13:57:46 +00004499 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
4500 nestedNameSpecifier()));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004501
4502 EXPECT_TRUE(matches(
4503 "struct A { static void f() {} }; void g() { A::f(); }",
4504 nestedNameSpecifier()));
4505 EXPECT_TRUE(notMatches(
4506 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4507 nestedNameSpecifier()));
4508}
4509
Daniel Jasper87c3d362012-09-20 14:12:57 +00004510TEST(NullStatement, SimpleCases) {
4511 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4512 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4513}
4514
Aaron Ballman11825f22015-08-18 19:55:20 +00004515TEST(NS, Anonymous) {
4516 EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
4517 EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
4518}
4519
Aaron Ballman6c79f352015-08-28 19:39:21 +00004520TEST(NS, Alias) {
4521 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
4522 namespaceAliasDecl(hasName("alias"))));
4523}
4524
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004525TEST(NNS, MatchesTypes) {
4526 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4527 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4528 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4529 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4530 Matcher));
4531 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4532}
4533
4534TEST(NNS, MatchesNamespaceDecls) {
4535 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4536 specifiesNamespace(hasName("ns")));
4537 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4538 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4539 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4540}
4541
4542TEST(NNS, BindsNestedNameSpecifiers) {
4543 EXPECT_TRUE(matchAndVerifyResultTrue(
4544 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4545 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4546 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4547}
4548
4549TEST(NNS, BindsNestedNameSpecifierLocs) {
4550 EXPECT_TRUE(matchAndVerifyResultTrue(
4551 "namespace ns { struct B {}; } ns::B b;",
4552 loc(nestedNameSpecifier()).bind("loc"),
4553 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4554}
4555
4556TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4557 EXPECT_TRUE(matches(
4558 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4559 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4560 EXPECT_TRUE(matches(
4561 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004562 nestedNameSpecifierLoc(hasPrefix(
4563 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004564}
4565
Daniel Jasper6fc34332012-10-30 15:42:00 +00004566TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4567 std::string Fragment =
4568 "namespace a { struct A { struct B { struct C {}; }; }; };"
4569 "void f() { a::A::B::C c; }";
4570 EXPECT_TRUE(matches(
4571 Fragment,
4572 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4573 hasDescendant(nestedNameSpecifier(
4574 specifiesNamespace(hasName("a")))))));
4575 EXPECT_TRUE(notMatches(
4576 Fragment,
4577 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4578 has(nestedNameSpecifier(
4579 specifiesNamespace(hasName("a")))))));
4580 EXPECT_TRUE(matches(
4581 Fragment,
4582 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4583 has(nestedNameSpecifier(
4584 specifiesNamespace(hasName("a")))))));
4585
4586 // Not really useful because a NestedNameSpecifier can af at most one child,
4587 // but to complete the interface.
4588 EXPECT_TRUE(matchAndVerifyResultTrue(
4589 Fragment,
4590 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4591 forEach(nestedNameSpecifier().bind("x"))),
4592 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4593}
4594
4595TEST(NNS, NestedNameSpecifiersAsDescendants) {
4596 std::string Fragment =
4597 "namespace a { struct A { struct B { struct C {}; }; }; };"
4598 "void f() { a::A::B::C c; }";
4599 EXPECT_TRUE(matches(
4600 Fragment,
4601 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4602 asString("struct a::A")))))));
4603 EXPECT_TRUE(matchAndVerifyResultTrue(
4604 Fragment,
4605 functionDecl(hasName("f"),
4606 forEachDescendant(nestedNameSpecifier().bind("x"))),
4607 // Nested names: a, a::A and a::A::B.
4608 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4609}
4610
4611TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4612 std::string Fragment =
4613 "namespace a { struct A { struct B { struct C {}; }; }; };"
4614 "void f() { a::A::B::C c; }";
4615 EXPECT_TRUE(matches(
4616 Fragment,
4617 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4618 hasDescendant(loc(nestedNameSpecifier(
4619 specifiesNamespace(hasName("a"))))))));
4620 EXPECT_TRUE(notMatches(
4621 Fragment,
4622 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4623 has(loc(nestedNameSpecifier(
4624 specifiesNamespace(hasName("a"))))))));
4625 EXPECT_TRUE(matches(
4626 Fragment,
4627 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4628 has(loc(nestedNameSpecifier(
4629 specifiesNamespace(hasName("a"))))))));
4630
4631 EXPECT_TRUE(matchAndVerifyResultTrue(
4632 Fragment,
4633 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4634 forEach(nestedNameSpecifierLoc().bind("x"))),
4635 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4636}
4637
4638TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4639 std::string Fragment =
4640 "namespace a { struct A { struct B { struct C {}; }; }; };"
4641 "void f() { a::A::B::C c; }";
4642 EXPECT_TRUE(matches(
4643 Fragment,
4644 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4645 asString("struct a::A"))))))));
4646 EXPECT_TRUE(matchAndVerifyResultTrue(
4647 Fragment,
4648 functionDecl(hasName("f"),
4649 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4650 // Nested names: a, a::A and a::A::B.
4651 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4652}
4653
Manuel Klimek191c0932013-02-01 13:41:35 +00004654template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004655public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004656 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4657 StringRef InnerId)
4658 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004659 }
4660
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004661 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004662
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004663 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004664 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004665 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4666 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004667 }
4668private:
4669 std::string Id;
4670 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004671 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004672};
4673
4674TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004675 EXPECT_TRUE(matchAndVerifyResultTrue(
4676 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4677 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004678 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4679 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004680 EXPECT_TRUE(matchAndVerifyResultFalse(
4681 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4682 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004683 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4684 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004685}
4686
4687TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004688 EXPECT_TRUE(matchAndVerifyResultTrue(
4689 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004690 new VerifyMatchOnNode<clang::Stmt>(
4691 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004692 EXPECT_TRUE(matchAndVerifyResultFalse(
4693 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004694 new VerifyMatchOnNode<clang::Stmt>(
4695 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004696}
4697
4698TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4699 EXPECT_TRUE(matchAndVerifyResultTrue(
4700 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4701 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004702 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004703 EXPECT_TRUE(matchAndVerifyResultFalse(
4704 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4705 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004706 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004707}
4708
Manuel Klimekbee08572013-02-07 12:42:10 +00004709template <typename T>
4710class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4711public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004712 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004713
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004714 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004715 const T *Node = Nodes->getNodeAs<T>("");
4716 return verify(*Nodes, *Context, Node);
4717 }
4718
4719 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004720 // Use the original typed pointer to verify we can pass pointers to subtypes
4721 // to equalsNode.
4722 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004723 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004724 "", match(stmt(hasParent(
4725 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004726 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004727 }
4728 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004729 // Use the original typed pointer to verify we can pass pointers to subtypes
4730 // to equalsNode.
4731 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004732 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004733 "", match(decl(hasParent(
4734 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004735 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004736 }
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00004737 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
4738 // Use the original typed pointer to verify we can pass pointers to subtypes
4739 // to equalsNode.
4740 const T *TypedNode = cast<T>(Node);
4741 const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
4742 return selectFirst<T>(
4743 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
4744 hasType(type(equalsNode(TypedNode)).bind(""))))))),
4745 *Dec, Context)) != nullptr;
4746 }
Manuel Klimekbee08572013-02-07 12:42:10 +00004747};
4748
4749TEST(IsEqualTo, MatchesNodesByIdentity) {
4750 EXPECT_TRUE(matchAndVerifyResultTrue(
4751 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004752 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4753 EXPECT_TRUE(matchAndVerifyResultTrue(
4754 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4755 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00004756 EXPECT_TRUE(matchAndVerifyResultTrue(
4757 "class X { class Y {} y; };",
4758 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
4759 new VerifyAncestorHasChildIsEqual<Type>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004760}
4761
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004762TEST(MatchFinder, CheckProfiling) {
4763 MatchFinder::MatchFinderOptions Options;
4764 llvm::StringMap<llvm::TimeRecord> Records;
4765 Options.CheckProfiling.emplace(Records);
4766 MatchFinder Finder(std::move(Options));
4767
4768 struct NamedCallback : public MatchFinder::MatchCallback {
4769 void run(const MatchFinder::MatchResult &Result) override {}
4770 StringRef getID() const override { return "MyID"; }
4771 } Callback;
4772 Finder.addMatcher(decl(), &Callback);
4773 std::unique_ptr<FrontendActionFactory> Factory(
4774 newFrontendActionFactory(&Finder));
4775 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4776
4777 EXPECT_EQ(1u, Records.size());
4778 EXPECT_EQ("MyID", Records.begin()->getKey());
4779}
4780
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004781class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4782public:
4783 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004784 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004785 EXPECT_TRUE(Called);
4786 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004787 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004788 bool Called;
4789};
4790
4791TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4792 MatchFinder Finder;
4793 VerifyStartOfTranslationUnit VerifyCallback;
4794 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004795 std::unique_ptr<FrontendActionFactory> Factory(
4796 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004797 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4798 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004799
4800 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004801 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004802 ASSERT_TRUE(AST.get());
4803 Finder.matchAST(AST->getASTContext());
4804 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004805}
4806
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004807class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4808public:
4809 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004810 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004811 EXPECT_FALSE(Called);
4812 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004813 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004814 bool Called;
4815};
4816
4817TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4818 MatchFinder Finder;
4819 VerifyEndOfTranslationUnit VerifyCallback;
4820 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004821 std::unique_ptr<FrontendActionFactory> Factory(
4822 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004823 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4824 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004825
4826 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004827 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004828 ASSERT_TRUE(AST.get());
4829 Finder.matchAST(AST->getASTContext());
4830 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004831}
4832
Manuel Klimekbbb75852013-06-20 14:06:32 +00004833TEST(EqualsBoundNodeMatcher, QualType) {
4834 EXPECT_TRUE(matches(
4835 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4836 hasInitializer(ignoringParenImpCasts(
4837 hasType(qualType(equalsBoundNode("type"))))))));
4838 EXPECT_TRUE(notMatches("int i = 1.f;",
4839 varDecl(hasType(qualType().bind("type")),
4840 hasInitializer(ignoringParenImpCasts(hasType(
4841 qualType(equalsBoundNode("type"))))))));
4842}
4843
4844TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4845 EXPECT_TRUE(notMatches(
4846 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4847 hasInitializer(ignoringParenImpCasts(
4848 hasType(qualType(equalsBoundNode("type"))))))));
4849}
4850
4851TEST(EqualsBoundNodeMatcher, Stmt) {
4852 EXPECT_TRUE(
4853 matches("void f() { if(true) {} }",
4854 stmt(allOf(ifStmt().bind("if"),
4855 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4856
4857 EXPECT_TRUE(notMatches(
4858 "void f() { if(true) { if (true) {} } }",
4859 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4860}
4861
4862TEST(EqualsBoundNodeMatcher, Decl) {
4863 EXPECT_TRUE(matches(
4864 "class X { class Y {}; };",
4865 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4866 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4867
4868 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4869 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4870 has(decl(equalsBoundNode("record")))))));
4871}
4872
4873TEST(EqualsBoundNodeMatcher, Type) {
4874 EXPECT_TRUE(matches(
4875 "class X { int a; int b; };",
4876 recordDecl(
4877 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4878 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4879
4880 EXPECT_TRUE(notMatches(
4881 "class X { int a; double b; };",
4882 recordDecl(
4883 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4884 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4885}
4886
4887TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004888 EXPECT_TRUE(matchAndVerifyResultTrue(
4889 "int f() {"
4890 " if (1) {"
4891 " int i = 9;"
4892 " }"
4893 " int j = 10;"
4894 " {"
4895 " float k = 9.0;"
4896 " }"
4897 " return 0;"
4898 "}",
4899 // Look for variable declarations within functions whose type is the same
4900 // as the function return type.
4901 functionDecl(returns(qualType().bind("type")),
4902 forEachDescendant(varDecl(hasType(
4903 qualType(equalsBoundNode("type")))).bind("decl"))),
4904 // Only i and j should match, not k.
4905 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4906}
4907
4908TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4909 EXPECT_TRUE(matchAndVerifyResultTrue(
4910 "void f() {"
4911 " int x;"
4912 " double d;"
4913 " x = d + x - d + x;"
4914 "}",
4915 functionDecl(
4916 hasName("f"), forEachDescendant(varDecl().bind("d")),
4917 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4918 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4919}
4920
Manuel Klimekce68f772014-03-25 14:39:26 +00004921TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4922 EXPECT_TRUE(matchAndVerifyResultTrue(
4923 "struct StringRef { int size() const; const char* data() const; };"
4924 "void f(StringRef v) {"
4925 " v.data();"
4926 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00004927 cxxMemberCallExpr(
4928 callee(cxxMethodDecl(hasName("data"))),
4929 on(declRefExpr(to(
4930 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
4931 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
4932 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
Manuel Klimekce68f772014-03-25 14:39:26 +00004933 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4934 .bind("data"),
4935 new VerifyIdIsBoundTo<Expr>("data", 1)));
4936
4937 EXPECT_FALSE(matches(
4938 "struct StringRef { int size() const; const char* data() const; };"
4939 "void f(StringRef v) {"
4940 " v.data();"
4941 " v.size();"
4942 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00004943 cxxMemberCallExpr(
4944 callee(cxxMethodDecl(hasName("data"))),
4945 on(declRefExpr(to(
4946 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
4947 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
4948 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
Manuel Klimekce68f772014-03-25 14:39:26 +00004949 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4950 .bind("data")));
4951}
4952
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004953TEST(TypeDefDeclMatcher, Match) {
4954 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4955 typedefDecl(hasName("typedefDeclTest"))));
4956}
4957
Aaron Ballman11825f22015-08-18 19:55:20 +00004958TEST(IsInlineMatcher, IsInline) {
4959 EXPECT_TRUE(matches("void g(); inline void f();",
4960 functionDecl(isInline(), hasName("f"))));
4961 EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
4962 namespaceDecl(isInline(), hasName("m"))));
4963}
4964
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004965// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4966#ifndef LLVM_ON_WIN32
4967
4968TEST(Matcher, IsExpansionInMainFileMatcher) {
4969 EXPECT_TRUE(matches("class X {};",
4970 recordDecl(hasName("X"), isExpansionInMainFile())));
4971 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4972 FileContentMappings M;
4973 M.push_back(std::make_pair("/other", "class X {};"));
4974 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4975 recordDecl(isExpansionInMainFile()), false,
4976 "-isystem/", M));
4977}
4978
4979TEST(Matcher, IsExpansionInSystemHeader) {
4980 FileContentMappings M;
4981 M.push_back(std::make_pair("/other", "class X {};"));
4982 EXPECT_TRUE(matchesConditionally(
4983 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4984 "-isystem/", M));
4985 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4986 recordDecl(isExpansionInSystemHeader()),
4987 false, "-I/", M));
4988 EXPECT_TRUE(notMatches("class X {};",
4989 recordDecl(isExpansionInSystemHeader())));
4990 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4991}
4992
4993TEST(Matcher, IsExpansionInFileMatching) {
4994 FileContentMappings M;
4995 M.push_back(std::make_pair("/foo", "class A {};"));
4996 M.push_back(std::make_pair("/bar", "class B {};"));
4997 EXPECT_TRUE(matchesConditionally(
4998 "#include <foo>\n"
4999 "#include <bar>\n"
5000 "class X {};",
5001 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
5002 "-isystem/", M));
5003 EXPECT_TRUE(matchesConditionally(
5004 "#include <foo>\n"
5005 "#include <bar>\n"
5006 "class X {};",
5007 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
5008 "-isystem/", M));
5009}
5010
5011#endif // LLVM_ON_WIN32
5012
Manuel Klimekbfa43572015-03-12 15:48:15 +00005013
5014TEST(ObjCMessageExprMatcher, SimpleExprs) {
5015 // don't find ObjCMessageExpr where none are present
5016 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
5017
5018 std::string Objc1String =
5019 "@interface Str "
5020 " - (Str *)uppercaseString:(Str *)str;"
5021 "@end "
5022 "@interface foo "
5023 "- (void)meth:(Str *)text;"
5024 "@end "
5025 " "
5026 "@implementation foo "
5027 "- (void) meth:(Str *)text { "
5028 " [self contents];"
5029 " Str *up = [text uppercaseString];"
5030 "} "
5031 "@end ";
5032 EXPECT_TRUE(matchesObjC(
5033 Objc1String,
5034 objcMessageExpr(anything())));
5035 EXPECT_TRUE(matchesObjC(
5036 Objc1String,
5037 objcMessageExpr(hasSelector("contents"))));
5038 EXPECT_TRUE(matchesObjC(
5039 Objc1String,
5040 objcMessageExpr(matchesSelector("cont*"))));
5041 EXPECT_FALSE(matchesObjC(
5042 Objc1String,
5043 objcMessageExpr(matchesSelector("?cont*"))));
5044 EXPECT_TRUE(notMatchesObjC(
5045 Objc1String,
5046 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
5047 EXPECT_TRUE(matchesObjC(
5048 Objc1String,
5049 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
5050 EXPECT_TRUE(matchesObjC(
5051 Objc1String,
Manuel Klimeke67a9d62015-09-08 10:11:26 +00005052 objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
5053 EXPECT_TRUE(matchesObjC(
5054 Objc1String,
Manuel Klimekbfa43572015-03-12 15:48:15 +00005055 objcMessageExpr(matchesSelector("uppercase*"),
5056 argumentCountIs(0)
5057 )));
5058
5059}
5060
Manuel Klimek04616e42012-07-06 05:48:52 +00005061} // end namespace ast_matchers
5062} // end namespace clang