blob: 46392dcd63adce02821fd4d21d7ea022d70084fc [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
Gabor Horvath009c5d52015-12-15 08:35:45 +00001472TEST(IsAnyCharacter, MatchesCharacters) {
1473 EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
1474}
1475
1476TEST(IsAnyCharacter, ReportsNoFalsePositives) {
1477 EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
1478}
1479
Manuel Klimek04616e42012-07-06 05:48:52 +00001480TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1481 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001482 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001483 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001484 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001485 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001486 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001487}
1488
1489TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1490 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001491 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001492 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001493 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001494 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001495 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001496}
1497
1498TEST(IsArrow, MatchesMemberCallsViaArrow) {
1499 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001500 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001501 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001502 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001503 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001504 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001505}
1506
1507TEST(Callee, MatchesDeclarations) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001508 StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001509
1510 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1511 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001512
Aaron Ballman512fb642015-09-17 13:30:52 +00001513 CallMethodX = callExpr(callee(cxxConversionDecl()));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001514 EXPECT_TRUE(
1515 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1516 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1517 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001518}
1519
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001520TEST(ConversionDeclaration, IsExplicit) {
1521 EXPECT_TRUE(matches("struct S { explicit operator int(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001522 cxxConversionDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001523 EXPECT_TRUE(notMatches("struct S { operator int(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001524 cxxConversionDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001525}
1526
Manuel Klimek04616e42012-07-06 05:48:52 +00001527TEST(Callee, MatchesMemberExpressions) {
1528 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001529 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001530 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001531 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001532}
1533
1534TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001535 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001536
1537 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1538 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1539
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001540 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1541 llvm::Triple::Win32) {
1542 // FIXME: Make this work for MSVC.
1543 // Dependent contexts, but a non-dependent call.
1544 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1545 CallFunctionF));
1546 EXPECT_TRUE(
1547 matches("void f(); template <int N> struct S { void g() { f(); } };",
1548 CallFunctionF));
1549 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001550
1551 // Depedent calls don't match.
1552 EXPECT_TRUE(
1553 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1554 CallFunctionF));
1555 EXPECT_TRUE(
1556 notMatches("void f(int);"
1557 "template <typename T> struct S { void g(T t) { f(t); } };",
1558 CallFunctionF));
Aaron Ballman3fd6c112015-10-05 14:41:27 +00001559
1560 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
1561 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
1562 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
1563 functionDecl(isVariadic())));
1564 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
1565 EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001566}
1567
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001568TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1569 EXPECT_TRUE(
1570 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001571 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001572}
1573
1574TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1575 EXPECT_TRUE(
1576 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001577 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001578}
1579
1580TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1581 EXPECT_TRUE(
1582 notMatches("void g(); template <typename T> void f(T t) {}"
1583 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001584 functionTemplateDecl(hasName("f"),
1585 hasDescendant(declRefExpr(to(
1586 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001587}
1588
Manuel Klimek04616e42012-07-06 05:48:52 +00001589TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001590 StatementMatcher CallArgumentY = callExpr(
1591 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001592
1593 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1594 EXPECT_TRUE(
1595 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1596 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1597
Daniel Jasper848cbe12012-09-18 13:09:13 +00001598 StatementMatcher WrongIndex = callExpr(
1599 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001600 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1601}
1602
1603TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001604 StatementMatcher CallArgumentY = callExpr(
1605 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001606 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1607 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1608 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1609}
1610
Manuel Klimekce28f9e2016-01-18 11:20:09 +00001611TEST(ForEachArgumentWithParam, ReportsNoFalsePositives) {
1612 StatementMatcher ArgumentY =
1613 declRefExpr(to(varDecl(hasName("y")))).bind("arg");
1614 DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
1615 StatementMatcher CallExpr =
1616 callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1617
1618 // IntParam does not match.
1619 EXPECT_FALSE(matches("void f(int* i) { int* y; f(y); }", CallExpr));
1620 // ArgumentY does not match.
1621 EXPECT_FALSE(matches("void f(int i) { int x; f(x); }", CallExpr));
1622}
1623
1624TEST(ForEachArgumentWithParam, MatchesCXXMemberCallExpr) {
1625 StatementMatcher ArgumentY =
1626 declRefExpr(to(varDecl(hasName("y")))).bind("arg");
1627 DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
1628 StatementMatcher CallExpr =
1629 callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1630 EXPECT_TRUE(matchAndVerifyResultTrue(
1631 "struct S {"
1632 " const S& operator[](int i) { return *this; }"
1633 "};"
1634 "void f(S S1) {"
1635 " int y = 1;"
1636 " S1[y];"
1637 "}",
1638 CallExpr, new VerifyIdIsBoundTo<ParmVarDecl>("param", 1)));
1639}
1640
1641TEST(ForEachArgumentWithParam, MatchesCallExpr) {
1642 StatementMatcher ArgumentY =
1643 declRefExpr(to(varDecl(hasName("y")))).bind("arg");
1644 DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
1645 StatementMatcher CallExpr =
1646 callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1647
1648 EXPECT_TRUE(
1649 matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr,
1650 new VerifyIdIsBoundTo<ParmVarDecl>("param")));
1651 EXPECT_TRUE(
1652 matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr,
1653 new VerifyIdIsBoundTo<DeclRefExpr>("arg")));
1654
1655 EXPECT_TRUE(matchAndVerifyResultTrue(
1656 "void f(int i, int j) { int y; f(y, y); }", CallExpr,
1657 new VerifyIdIsBoundTo<ParmVarDecl>("param", 2)));
1658 EXPECT_TRUE(matchAndVerifyResultTrue(
1659 "void f(int i, int j) { int y; f(y, y); }", CallExpr,
1660 new VerifyIdIsBoundTo<DeclRefExpr>("arg", 2)));
1661}
1662
1663TEST(ForEachArgumentWithParam, MatchesConstructExpr) {
1664 StatementMatcher ArgumentY =
1665 declRefExpr(to(varDecl(hasName("y")))).bind("arg");
1666 DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
1667 StatementMatcher ConstructExpr =
1668 cxxConstructExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1669
1670 EXPECT_TRUE(matchAndVerifyResultTrue(
1671 "struct C {"
1672 " C(int i) {}"
1673 "};"
1674 "int y = 0;"
1675 "C Obj(y);",
1676 ConstructExpr, new VerifyIdIsBoundTo<ParmVarDecl>("param")));
1677}
1678
1679TEST(ForEachArgumentWithParam, HandlesBoundNodesForNonMatches) {
1680 EXPECT_TRUE(matchAndVerifyResultTrue(
1681 "void g(int i, int j) {"
1682 " int a;"
1683 " int b;"
1684 " int c;"
1685 " g(a, 0);"
1686 " g(a, b);"
1687 " g(0, b);"
1688 "}",
1689 functionDecl(
1690 forEachDescendant(varDecl().bind("v")),
1691 forEachDescendant(callExpr(forEachArgumentWithParam(
1692 declRefExpr(to(decl(equalsBoundNode("v")))), parmVarDecl())))),
1693 new VerifyIdIsBoundTo<VarDecl>("v", 4)));
1694}
1695
Manuel Klimek04616e42012-07-06 05:48:52 +00001696TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001697 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001698
1699 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1700 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1701 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1702}
1703
Daniel Jasper9f501292012-12-04 11:54:27 +00001704TEST(Matcher, ParameterCount) {
1705 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1706 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1707 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1708 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1709 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1710}
1711
Manuel Klimek04616e42012-07-06 05:48:52 +00001712TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001713 DeclarationMatcher ReferenceClassX = varDecl(
1714 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001715 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1716 ReferenceClassX));
1717 EXPECT_TRUE(
1718 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001719 // The match here is on the implicit copy constructor code for
1720 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001721 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001722 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1723 EXPECT_TRUE(
1724 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001725 EXPECT_TRUE(
1726 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1727}
1728
Edwin Vane0a4836e2013-03-06 17:02:57 +00001729TEST(QualType, hasCanonicalType) {
1730 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1731 "int a;"
1732 "int_ref b = a;",
1733 varDecl(hasType(qualType(referenceType())))));
1734 EXPECT_TRUE(
1735 matches("typedef int &int_ref;"
1736 "int a;"
1737 "int_ref b = a;",
1738 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1739}
1740
Edwin Vane119d3df2013-04-02 18:15:55 +00001741TEST(QualType, hasLocalQualifiers) {
1742 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1743 varDecl(hasType(hasLocalQualifiers()))));
1744 EXPECT_TRUE(matches("int *const j = nullptr;",
1745 varDecl(hasType(hasLocalQualifiers()))));
1746 EXPECT_TRUE(matches("int *volatile k;",
1747 varDecl(hasType(hasLocalQualifiers()))));
1748 EXPECT_TRUE(notMatches("int m;",
1749 varDecl(hasType(hasLocalQualifiers()))));
1750}
1751
Manuel Klimek04616e42012-07-06 05:48:52 +00001752TEST(HasParameter, CallsInnerMatcher) {
1753 EXPECT_TRUE(matches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001754 cxxMethodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001755 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001756 cxxMethodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001757}
1758
1759TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1760 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001761 cxxMethodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001762}
1763
1764TEST(HasType, MatchesParameterVariableTypesStrictly) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001765 EXPECT_TRUE(matches(
1766 "class X { void x(X x) {} };",
1767 cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
1768 EXPECT_TRUE(notMatches(
1769 "class X { void x(const X &x) {} };",
1770 cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001771 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001772 cxxMethodDecl(hasParameter(
1773 0, hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001774 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001775 cxxMethodDecl(hasParameter(
1776 0, hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001777}
1778
1779TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001780 EXPECT_TRUE(matches(
1781 "class Y {}; class X { void x(X x, Y y) {} };",
1782 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
1783 EXPECT_TRUE(matches(
1784 "class Y {}; class X { void x(Y y, X x) {} };",
1785 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001786}
1787
Daniel Jasper1dad1832012-07-10 20:20:19 +00001788TEST(Returns, MatchesReturnTypes) {
1789 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001790 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001791 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001792 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001793 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001794 functionDecl(returns(hasDeclaration(
1795 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001796}
1797
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001798TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001799 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1800 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1801 functionDecl(isExternC())));
1802 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001803}
1804
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001805TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1806 EXPECT_TRUE(
1807 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1808 EXPECT_TRUE(matches("void Func() = delete;",
1809 functionDecl(hasName("Func"), isDeleted())));
1810}
1811
Aaron Ballmana60bcda2015-12-02 15:23:59 +00001812TEST(IsNoThrow, MatchesNoThrowFunctionDeclarations) {
1813 EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
1814 EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
1815 EXPECT_TRUE(
1816 notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
1817 EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
1818 EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
1819}
1820
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001821TEST(isConstexpr, MatchesConstexprDeclarations) {
1822 EXPECT_TRUE(matches("constexpr int foo = 42;",
1823 varDecl(hasName("foo"), isConstexpr())));
1824 EXPECT_TRUE(matches("constexpr int bar();",
1825 functionDecl(hasName("bar"), isConstexpr())));
1826}
1827
Manuel Klimek04616e42012-07-06 05:48:52 +00001828TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001829 EXPECT_TRUE(notMatches(
1830 "class Y {}; class X { void x(int) {} };",
1831 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001832}
1833
1834TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1835 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001836 cxxMethodDecl(hasAnyParameter(
1837 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001838}
1839
Alp Toker8db6e7a2014-01-05 06:38:57 +00001840TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001841 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001842 cxxMethodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001843 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001844 cxxMethodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001845}
1846
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001847TEST(Matcher, MatchesClassTemplateSpecialization) {
1848 EXPECT_TRUE(matches("template<typename T> struct A {};"
1849 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001850 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001851 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001852 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001853 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001854 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001855}
1856
Manuel Klimekc16c6522013-06-20 13:08:29 +00001857TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1858 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1859 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1860}
1861
1862TEST(ParmVarDecl, MatchesParmVars) {
1863 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1864 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1865}
1866
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001867TEST(Matcher, MatchesTypeTemplateArgument) {
1868 EXPECT_TRUE(matches(
1869 "template<typename T> struct B {};"
1870 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001871 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001872 asString("int"))))));
1873}
1874
1875TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1876 EXPECT_TRUE(matches(
1877 "struct B { int next; };"
1878 "template<int(B::*next_ptr)> struct A {};"
1879 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001880 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1881 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001882
1883 EXPECT_TRUE(notMatches(
1884 "template <typename T> struct A {};"
1885 "A<int> a;",
1886 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1887 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001888
1889 EXPECT_TRUE(matches(
1890 "struct B { int next; };"
1891 "template<int(B::*next_ptr)> struct A {};"
1892 "A<&B::next> a;",
1893 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1894 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1895
1896 EXPECT_TRUE(notMatches(
1897 "template <typename T> struct A {};"
1898 "A<int> a;",
1899 templateSpecializationType(hasAnyTemplateArgument(
1900 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001901}
1902
1903TEST(Matcher, MatchesSpecificArgument) {
1904 EXPECT_TRUE(matches(
1905 "template<typename T, typename U> class A {};"
1906 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001907 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001908 1, refersToType(asString("int"))))));
1909 EXPECT_TRUE(notMatches(
1910 "template<typename T, typename U> class A {};"
1911 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001912 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001913 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001914
1915 EXPECT_TRUE(matches(
1916 "template<typename T, typename U> class A {};"
1917 "A<bool, int> a;",
1918 templateSpecializationType(hasTemplateArgument(
1919 1, refersToType(asString("int"))))));
1920 EXPECT_TRUE(notMatches(
1921 "template<typename T, typename U> class A {};"
1922 "A<int, bool> a;",
1923 templateSpecializationType(hasTemplateArgument(
1924 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001925}
1926
Manuel Klimek7735e402014-10-09 13:06:22 +00001927TEST(TemplateArgument, Matches) {
1928 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1929 classTemplateSpecializationDecl(
1930 hasAnyTemplateArgument(templateArgument()))));
1931 EXPECT_TRUE(matches(
1932 "template<typename T> struct C {}; C<int> c;",
1933 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1934}
1935
1936TEST(TemplateArgumentCountIs, Matches) {
1937 EXPECT_TRUE(
1938 matches("template<typename T> struct C {}; C<int> c;",
1939 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1940 EXPECT_TRUE(
1941 notMatches("template<typename T> struct C {}; C<int> c;",
1942 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1943
1944 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1945 templateSpecializationType(templateArgumentCountIs(1))));
1946 EXPECT_TRUE(
1947 notMatches("template<typename T> struct C {}; C<int> c;",
1948 templateSpecializationType(templateArgumentCountIs(2))));
1949}
1950
1951TEST(IsIntegral, Matches) {
1952 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1953 classTemplateSpecializationDecl(
1954 hasAnyTemplateArgument(isIntegral()))));
1955 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1956 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1957 templateArgument(isIntegral())))));
1958}
1959
1960TEST(RefersToIntegralType, Matches) {
1961 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1962 classTemplateSpecializationDecl(
1963 hasAnyTemplateArgument(refersToIntegralType(
1964 asString("int"))))));
1965 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1966 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1967 refersToIntegralType(asString("int"))))));
1968}
1969
1970TEST(EqualsIntegralValue, Matches) {
1971 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1972 classTemplateSpecializationDecl(
1973 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1974 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1975 classTemplateSpecializationDecl(
1976 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1977 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1978 classTemplateSpecializationDecl(
1979 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1980 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1981 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1982 equalsIntegralValue("0042")))));
1983}
1984
Daniel Jasper639522c2013-02-25 12:02:08 +00001985TEST(Matcher, MatchesAccessSpecDecls) {
1986 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1987 EXPECT_TRUE(
1988 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1989 EXPECT_TRUE(
1990 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1991 EXPECT_TRUE(
1992 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1993
1994 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1995}
1996
Aaron Ballman41143bb2015-07-24 12:35:41 +00001997TEST(Matcher, MatchesFinal) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001998 EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
Aaron Ballman41143bb2015-07-24 12:35:41 +00001999 EXPECT_TRUE(matches("class X { virtual void f() final; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002000 cxxMethodDecl(isFinal())));
2001 EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
2002 EXPECT_TRUE(
2003 notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
Aaron Ballman41143bb2015-07-24 12:35:41 +00002004}
2005
Edwin Vane37ee1d72013-04-09 20:46:36 +00002006TEST(Matcher, MatchesVirtualMethod) {
2007 EXPECT_TRUE(matches("class X { virtual int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002008 cxxMethodDecl(isVirtual(), hasName("::X::f"))));
2009 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002010}
2011
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00002012TEST(Matcher, MatchesPureMethod) {
2013 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002014 cxxMethodDecl(isPure(), hasName("::X::f"))));
2015 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00002016}
2017
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00002018TEST(Matcher, MatchesCopyAssignmentOperator) {
2019 EXPECT_TRUE(matches("class X { X &operator=(X); };",
2020 cxxMethodDecl(isCopyAssignmentOperator())));
2021 EXPECT_TRUE(matches("class X { X &operator=(X &); };",
2022 cxxMethodDecl(isCopyAssignmentOperator())));
2023 EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
2024 cxxMethodDecl(isCopyAssignmentOperator())));
2025 EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
2026 cxxMethodDecl(isCopyAssignmentOperator())));
2027 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
2028 cxxMethodDecl(isCopyAssignmentOperator())));
2029 EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
2030 cxxMethodDecl(isCopyAssignmentOperator())));
2031}
2032
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00002033TEST(Matcher, MatchesConstMethod) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002034 EXPECT_TRUE(
2035 matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
2036 EXPECT_TRUE(
2037 notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00002038}
2039
Edwin Vane37ee1d72013-04-09 20:46:36 +00002040TEST(Matcher, MatchesOverridingMethod) {
2041 EXPECT_TRUE(matches("class X { virtual int f(); }; "
2042 "class Y : public X { int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002043 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002044 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
Aaron Ballman512fb642015-09-17 13:30:52 +00002045 "class Y : public X { int f(); };",
2046 cxxMethodDecl(isOverride(), hasName("::X::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002047 EXPECT_TRUE(notMatches("class X { int f(); }; "
2048 "class Y : public X { int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002049 cxxMethodDecl(isOverride())));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002050 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
Aaron Ballman512fb642015-09-17 13:30:52 +00002051 cxxMethodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00002052 EXPECT_TRUE(
2053 matches("template <typename Base> struct Y : Base { void f() override;};",
Aaron Ballman512fb642015-09-17 13:30:52 +00002054 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002055}
2056
Manuel Klimek04616e42012-07-06 05:48:52 +00002057TEST(Matcher, ConstructorCall) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002058 StatementMatcher Constructor = cxxConstructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002059
2060 EXPECT_TRUE(
2061 matches("class X { public: X(); }; void x() { X x; }", Constructor));
2062 EXPECT_TRUE(
2063 matches("class X { public: X(); }; void x() { X x = X(); }",
2064 Constructor));
2065 EXPECT_TRUE(
2066 matches("class X { public: X(int); }; void x() { X x = 0; }",
2067 Constructor));
2068 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
2069}
2070
2071TEST(Matcher, ConstructorArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002072 StatementMatcher Constructor = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002073 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002074
2075 EXPECT_TRUE(
2076 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
2077 Constructor));
2078 EXPECT_TRUE(
2079 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
2080 Constructor));
2081 EXPECT_TRUE(
2082 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
2083 Constructor));
2084 EXPECT_TRUE(
2085 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
2086 Constructor));
2087
Aaron Ballman512fb642015-09-17 13:30:52 +00002088 StatementMatcher WrongIndex = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002089 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002090 EXPECT_TRUE(
2091 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
2092 WrongIndex));
2093}
2094
2095TEST(Matcher, ConstructorArgumentCount) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002096 StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002097
2098 EXPECT_TRUE(
2099 matches("class X { public: X(int); }; void x() { X x(0); }",
2100 Constructor1Arg));
2101 EXPECT_TRUE(
2102 matches("class X { public: X(int); }; void x() { X x = X(0); }",
2103 Constructor1Arg));
2104 EXPECT_TRUE(
2105 matches("class X { public: X(int); }; void x() { X x = 0; }",
2106 Constructor1Arg));
2107 EXPECT_TRUE(
2108 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
2109 Constructor1Arg));
2110}
2111
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00002112TEST(Matcher, ConstructorListInitialization) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002113 StatementMatcher ConstructorListInit =
2114 cxxConstructExpr(isListInitialization());
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00002115
2116 EXPECT_TRUE(
2117 matches("class X { public: X(int); }; void x() { X x{0}; }",
2118 ConstructorListInit));
2119 EXPECT_FALSE(
2120 matches("class X { public: X(int); }; void x() { X x(0); }",
2121 ConstructorListInit));
2122}
2123
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002124TEST(Matcher,ThisExpr) {
2125 EXPECT_TRUE(
Aaron Ballman512fb642015-09-17 13:30:52 +00002126 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002127 EXPECT_TRUE(
Aaron Ballman512fb642015-09-17 13:30:52 +00002128 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002129}
2130
Manuel Klimek04616e42012-07-06 05:48:52 +00002131TEST(Matcher, BindTemporaryExpression) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002132 StatementMatcher TempExpression = cxxBindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002133
2134 std::string ClassString = "class string { public: string(); ~string(); }; ";
2135
2136 EXPECT_TRUE(
2137 matches(ClassString +
2138 "string GetStringByValue();"
2139 "void FunctionTakesString(string s);"
2140 "void run() { FunctionTakesString(GetStringByValue()); }",
2141 TempExpression));
2142
2143 EXPECT_TRUE(
2144 notMatches(ClassString +
2145 "string* GetStringPointer(); "
2146 "void FunctionTakesStringPtr(string* s);"
2147 "void run() {"
2148 " string* s = GetStringPointer();"
2149 " FunctionTakesStringPtr(GetStringPointer());"
2150 " FunctionTakesStringPtr(s);"
2151 "}",
2152 TempExpression));
2153
2154 EXPECT_TRUE(
2155 notMatches("class no_dtor {};"
2156 "no_dtor GetObjByValue();"
2157 "void ConsumeObj(no_dtor param);"
2158 "void run() { ConsumeObj(GetObjByValue()); }",
2159 TempExpression));
2160}
2161
Sam Panzer68a35af2012-08-24 22:04:44 +00002162TEST(MaterializeTemporaryExpr, MatchesTemporary) {
2163 std::string ClassString =
2164 "class string { public: string(); int length(); }; ";
2165
2166 EXPECT_TRUE(
2167 matches(ClassString +
2168 "string GetStringByValue();"
2169 "void FunctionTakesString(string s);"
2170 "void run() { FunctionTakesString(GetStringByValue()); }",
2171 materializeTemporaryExpr()));
2172
2173 EXPECT_TRUE(
2174 notMatches(ClassString +
2175 "string* GetStringPointer(); "
2176 "void FunctionTakesStringPtr(string* s);"
2177 "void run() {"
2178 " string* s = GetStringPointer();"
2179 " FunctionTakesStringPtr(GetStringPointer());"
2180 " FunctionTakesStringPtr(s);"
2181 "}",
2182 materializeTemporaryExpr()));
2183
2184 EXPECT_TRUE(
2185 notMatches(ClassString +
2186 "string GetStringByValue();"
2187 "void run() { int k = GetStringByValue().length(); }",
2188 materializeTemporaryExpr()));
2189
2190 EXPECT_TRUE(
2191 notMatches(ClassString +
2192 "string GetStringByValue();"
2193 "void run() { GetStringByValue(); }",
2194 materializeTemporaryExpr()));
2195}
2196
Manuel Klimek04616e42012-07-06 05:48:52 +00002197TEST(ConstructorDeclaration, SimpleCase) {
2198 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002199 cxxConstructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002200 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002201 cxxConstructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002202}
2203
2204TEST(ConstructorDeclaration, IsImplicit) {
2205 // This one doesn't match because the constructor is not added by the
2206 // compiler (it is not needed).
2207 EXPECT_TRUE(notMatches("class Foo { };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002208 cxxConstructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002209 // The compiler added the implicit default constructor.
2210 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Aaron Ballman512fb642015-09-17 13:30:52 +00002211 cxxConstructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002212 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002213 cxxConstructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00002214 // The compiler added an implicit assignment operator.
2215 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002216 cxxMethodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002217}
2218
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002219TEST(ConstructorDeclaration, IsExplicit) {
2220 EXPECT_TRUE(matches("struct S { explicit S(int); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002221 cxxConstructorDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002222 EXPECT_TRUE(notMatches("struct S { S(int); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002223 cxxConstructorDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002224}
2225
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002226TEST(ConstructorDeclaration, Kinds) {
2227 EXPECT_TRUE(matches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002228 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002229 EXPECT_TRUE(notMatches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002230 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002231 EXPECT_TRUE(notMatches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002232 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002233
2234 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002235 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002236 EXPECT_TRUE(matches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002237 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002238 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002239 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002240
2241 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002242 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002243 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002244 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002245 EXPECT_TRUE(matches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002246 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002247}
2248
Daniel Jasper1dad1832012-07-10 20:20:19 +00002249TEST(DestructorDeclaration, MatchesVirtualDestructor) {
2250 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002251 cxxDestructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002252}
2253
2254TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002255 EXPECT_TRUE(notMatches("class Foo {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00002256 cxxDestructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002257}
2258
Manuel Klimek04616e42012-07-06 05:48:52 +00002259TEST(HasAnyConstructorInitializer, SimpleCase) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002260 EXPECT_TRUE(
2261 notMatches("class Foo { Foo() { } };",
2262 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
2263 EXPECT_TRUE(
2264 matches("class Foo {"
2265 " Foo() : foo_() { }"
2266 " int foo_;"
2267 "};",
2268 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002269}
2270
2271TEST(HasAnyConstructorInitializer, ForField) {
2272 static const char Code[] =
2273 "class Baz { };"
2274 "class Foo {"
2275 " Foo() : foo_() { }"
2276 " Baz foo_;"
2277 " Baz bar_;"
2278 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002279 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002280 forField(hasType(recordDecl(hasName("Baz"))))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002281 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002282 forField(hasName("foo_"))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002283 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002284 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002285}
2286
2287TEST(HasAnyConstructorInitializer, WithInitializer) {
2288 static const char Code[] =
2289 "class Foo {"
2290 " Foo() : foo_(0) { }"
2291 " int foo_;"
2292 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002293 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002294 withInitializer(integerLiteral(equals(0)))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002295 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002296 withInitializer(integerLiteral(equals(1)))))));
2297}
2298
2299TEST(HasAnyConstructorInitializer, IsWritten) {
2300 static const char Code[] =
2301 "struct Bar { Bar(){} };"
2302 "class Foo {"
2303 " Foo() : foo_() { }"
2304 " Bar foo_;"
2305 " Bar bar_;"
2306 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002307 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002308 allOf(forField(hasName("foo_")), isWritten())))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002309 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002310 allOf(forField(hasName("bar_")), isWritten())))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002311 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002312 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2313}
2314
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002315TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
2316 static const char Code[] =
2317 "struct B {};"
2318 "struct D : B {"
2319 " int I;"
2320 " D(int i) : I(i) {}"
2321 "};"
2322 "struct E : B {"
2323 " E() : B() {}"
2324 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002325 EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002326 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2327 hasName("E")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002328 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002329 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2330 hasName("D")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002331 EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
Aaron Ballmaned455d42015-08-11 20:42:00 +00002332 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2333 hasName("D")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002334 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
Aaron Ballmaned455d42015-08-11 20:42:00 +00002335 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2336 hasName("E")))));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002337}
2338
Manuel Klimek04616e42012-07-06 05:48:52 +00002339TEST(Matcher, NewExpression) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002340 StatementMatcher New = cxxNewExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002341
2342 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2343 EXPECT_TRUE(
2344 matches("class X { public: X(); }; void x() { new X(); }", New));
2345 EXPECT_TRUE(
2346 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2347 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2348}
2349
2350TEST(Matcher, NewExpressionArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002351 StatementMatcher New = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002352 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002353
2354 EXPECT_TRUE(
2355 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2356 New));
2357 EXPECT_TRUE(
2358 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2359 New));
2360 EXPECT_TRUE(
2361 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2362 New));
2363
Aaron Ballman512fb642015-09-17 13:30:52 +00002364 StatementMatcher WrongIndex = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002365 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002366 EXPECT_TRUE(
2367 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2368 WrongIndex));
2369}
2370
2371TEST(Matcher, NewExpressionArgumentCount) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002372 StatementMatcher New = cxxConstructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002373
2374 EXPECT_TRUE(
2375 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2376 EXPECT_TRUE(
2377 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2378 New));
2379}
2380
Daniel Jasper1dad1832012-07-10 20:20:19 +00002381TEST(Matcher, DeleteExpression) {
2382 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002383 cxxDeleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002384}
2385
Manuel Klimek04616e42012-07-06 05:48:52 +00002386TEST(Matcher, DefaultArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002387 StatementMatcher Arg = cxxDefaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002388
2389 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2390 EXPECT_TRUE(
2391 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2392 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2393}
2394
2395TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002396 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002397 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2398 // wide string
2399 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2400 // with escaped characters
2401 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2402 // no matching -- though the data type is the same, there is no string literal
2403 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2404}
2405
2406TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002407 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002408 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2409 // wide character
2410 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2411 // wide character, Hex encoded, NOT MATCHED!
2412 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2413 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2414}
2415
2416TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002417 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002418 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2419 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2420 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2421 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2422
2423 // Non-matching cases (character literals, float and double)
2424 EXPECT_TRUE(notMatches("int i = L'a';",
2425 HasIntLiteral)); // this is actually a character
2426 // literal cast to int
2427 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2428 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2429 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2430}
2431
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002432TEST(Matcher, FloatLiterals) {
2433 StatementMatcher HasFloatLiteral = floatLiteral();
2434 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2435 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2436 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2437 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2438 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002439 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2440 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2441 EXPECT_TRUE(
2442 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002443
2444 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002445 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2446 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2447 EXPECT_TRUE(
2448 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002449}
2450
Daniel Jasper5901e472012-10-01 13:40:41 +00002451TEST(Matcher, NullPtrLiteral) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002452 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
Daniel Jasper5901e472012-10-01 13:40:41 +00002453}
2454
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002455TEST(Matcher, GNUNullExpr) {
2456 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2457}
2458
Daniel Jasper87c3d362012-09-20 14:12:57 +00002459TEST(Matcher, AsmStatement) {
2460 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2461}
2462
Manuel Klimek04616e42012-07-06 05:48:52 +00002463TEST(Matcher, Conditions) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002464 StatementMatcher Condition =
2465 ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002466
2467 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2468 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2469 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2470 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2471 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2472}
2473
Manuel Klimek909b5c942014-05-27 10:04:12 +00002474TEST(IfStmt, ChildTraversalMatchers) {
2475 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002476 ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002477 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002478 ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002479 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002480 ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002481 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002482 ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002483}
2484
Manuel Klimek04616e42012-07-06 05:48:52 +00002485TEST(MatchBinaryOperator, HasOperatorName) {
2486 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2487
2488 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2489 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2490}
2491
2492TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2493 StatementMatcher OperatorTrueFalse =
Aaron Ballman512fb642015-09-17 13:30:52 +00002494 binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
2495 hasRHS(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002496
2497 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2498 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2499 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
Alexander Kornienkoe39993e2015-11-02 22:23:21 +00002500
2501 StatementMatcher OperatorIntPointer = arraySubscriptExpr(
2502 hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
2503 EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
2504 EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
Manuel Klimek04616e42012-07-06 05:48:52 +00002505}
2506
2507TEST(MatchBinaryOperator, HasEitherOperand) {
2508 StatementMatcher HasOperand =
Aaron Ballman512fb642015-09-17 13:30:52 +00002509 binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002510
2511 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2512 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2513 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2514}
2515
2516TEST(Matcher, BinaryOperatorTypes) {
2517 // Integration test that verifies the AST provides all binary operators in
2518 // a way we expect.
2519 // FIXME: Operator ','
2520 EXPECT_TRUE(
2521 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2522 EXPECT_TRUE(
2523 matches("bool b; bool c = (b = true);",
2524 binaryOperator(hasOperatorName("="))));
2525 EXPECT_TRUE(
2526 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2527 EXPECT_TRUE(
2528 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2529 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2530 EXPECT_TRUE(
2531 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2532 EXPECT_TRUE(
2533 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2534 EXPECT_TRUE(
2535 matches("int i = 1; int j = (i <<= 2);",
2536 binaryOperator(hasOperatorName("<<="))));
2537 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2538 EXPECT_TRUE(
2539 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2540 EXPECT_TRUE(
2541 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2542 EXPECT_TRUE(
2543 matches("int i = 1; int j = (i >>= 2);",
2544 binaryOperator(hasOperatorName(">>="))));
2545 EXPECT_TRUE(
2546 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2547 EXPECT_TRUE(
2548 matches("int i = 42; int j = (i ^= 42);",
2549 binaryOperator(hasOperatorName("^="))));
2550 EXPECT_TRUE(
2551 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2552 EXPECT_TRUE(
2553 matches("int i = 42; int j = (i %= 42);",
2554 binaryOperator(hasOperatorName("%="))));
2555 EXPECT_TRUE(
2556 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2557 EXPECT_TRUE(
2558 matches("bool b = true && false;",
2559 binaryOperator(hasOperatorName("&&"))));
2560 EXPECT_TRUE(
2561 matches("bool b = true; bool c = (b &= false);",
2562 binaryOperator(hasOperatorName("&="))));
2563 EXPECT_TRUE(
2564 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2565 EXPECT_TRUE(
2566 matches("bool b = true || false;",
2567 binaryOperator(hasOperatorName("||"))));
2568 EXPECT_TRUE(
2569 matches("bool b = true; bool c = (b |= false);",
2570 binaryOperator(hasOperatorName("|="))));
2571 EXPECT_TRUE(
2572 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2573 EXPECT_TRUE(
2574 matches("int i = 42; int j = (i *= 23);",
2575 binaryOperator(hasOperatorName("*="))));
2576 EXPECT_TRUE(
2577 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2578 EXPECT_TRUE(
2579 matches("int i = 42; int j = (i /= 23);",
2580 binaryOperator(hasOperatorName("/="))));
2581 EXPECT_TRUE(
2582 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2583 EXPECT_TRUE(
2584 matches("int i = 42; int j = (i += 23);",
2585 binaryOperator(hasOperatorName("+="))));
2586 EXPECT_TRUE(
2587 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2588 EXPECT_TRUE(
2589 matches("int i = 42; int j = (i -= 23);",
2590 binaryOperator(hasOperatorName("-="))));
2591 EXPECT_TRUE(
2592 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2593 binaryOperator(hasOperatorName("->*"))));
2594 EXPECT_TRUE(
2595 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2596 binaryOperator(hasOperatorName(".*"))));
2597
2598 // Member expressions as operators are not supported in matches.
2599 EXPECT_TRUE(
2600 notMatches("struct A { void x(A *a) { a->x(this); } };",
2601 binaryOperator(hasOperatorName("->"))));
2602
2603 // Initializer assignments are not represented as operator equals.
2604 EXPECT_TRUE(
2605 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2606
2607 // Array indexing is not represented as operator.
2608 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2609
2610 // Overloaded operators do not match at all.
2611 EXPECT_TRUE(notMatches(
2612 "struct A { bool operator&&(const A &a) const { return false; } };"
2613 "void x() { A a, b; a && b; }",
2614 binaryOperator()));
2615}
2616
2617TEST(MatchUnaryOperator, HasOperatorName) {
2618 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2619
2620 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2621 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2622}
2623
2624TEST(MatchUnaryOperator, HasUnaryOperand) {
2625 StatementMatcher OperatorOnFalse =
Aaron Ballman512fb642015-09-17 13:30:52 +00002626 unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002627
2628 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2629 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2630}
2631
2632TEST(Matcher, UnaryOperatorTypes) {
2633 // Integration test that verifies the AST provides all unary operators in
2634 // a way we expect.
2635 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2636 EXPECT_TRUE(
2637 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2638 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2639 EXPECT_TRUE(
2640 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2641 EXPECT_TRUE(
2642 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2643 EXPECT_TRUE(
2644 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2645 EXPECT_TRUE(
2646 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2647 EXPECT_TRUE(
2648 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2649 EXPECT_TRUE(
2650 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2651 EXPECT_TRUE(
2652 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2653
2654 // We don't match conversion operators.
2655 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2656
2657 // Function calls are not represented as operator.
2658 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2659
2660 // Overloaded operators do not match at all.
2661 // FIXME: We probably want to add that.
2662 EXPECT_TRUE(notMatches(
2663 "struct A { bool operator!() const { return false; } };"
2664 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2665}
2666
2667TEST(Matcher, ConditionalOperator) {
2668 StatementMatcher Conditional = conditionalOperator(
Aaron Ballman512fb642015-09-17 13:30:52 +00002669 hasCondition(cxxBoolLiteral(equals(true))),
2670 hasTrueExpression(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002671
2672 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2673 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2674 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2675
2676 StatementMatcher ConditionalFalse = conditionalOperator(
Aaron Ballman512fb642015-09-17 13:30:52 +00002677 hasFalseExpression(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002678
2679 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2680 EXPECT_TRUE(
2681 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2682}
2683
Daniel Jasper1dad1832012-07-10 20:20:19 +00002684TEST(ArraySubscriptMatchers, ArraySubscripts) {
2685 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2686 arraySubscriptExpr()));
2687 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2688 arraySubscriptExpr()));
2689}
2690
2691TEST(ArraySubscriptMatchers, ArrayIndex) {
2692 EXPECT_TRUE(matches(
2693 "int i[2]; void f() { i[1] = 1; }",
2694 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2695 EXPECT_TRUE(matches(
2696 "int i[2]; void f() { 1[i] = 1; }",
2697 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2698 EXPECT_TRUE(notMatches(
2699 "int i[2]; void f() { i[1] = 1; }",
2700 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2701}
2702
2703TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2704 EXPECT_TRUE(matches(
2705 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002706 arraySubscriptExpr(hasBase(implicitCastExpr(
2707 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002708}
2709
Manuel Klimek04616e42012-07-06 05:48:52 +00002710TEST(Matcher, HasNameSupportsNamespaces) {
2711 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002712 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002713 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002714 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002715 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002716 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002717 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002718 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002719 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002720 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002721 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002722 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002723 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002724 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002725 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002726 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002727 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002728 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002729 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002730 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002731 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002732 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002733 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002734 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002735}
2736
2737TEST(Matcher, HasNameSupportsOuterClasses) {
2738 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002739 matches("class A { class B { class C; }; };",
2740 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002741 EXPECT_TRUE(
2742 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002743 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002744 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002745 matches("class A { class B { class C; }; };",
2746 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002747 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002748 matches("class A { class B { class C; }; };",
2749 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002750 EXPECT_TRUE(
2751 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002752 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002753 EXPECT_TRUE(
2754 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002755 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002756 EXPECT_TRUE(
2757 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002758 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002759 EXPECT_TRUE(
2760 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002761 recordDecl(hasName("::C"))));
2762 EXPECT_TRUE(
2763 notMatches("class A { class B { class C; }; };",
2764 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002765 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002766 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002767 EXPECT_TRUE(
2768 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002769 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002770}
2771
2772TEST(Matcher, IsDefinition) {
2773 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002774 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002775 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2776 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2777
2778 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002779 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002780 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2781 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2782
2783 DeclarationMatcher DefinitionOfMethodA =
Aaron Ballman512fb642015-09-17 13:30:52 +00002784 cxxMethodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002785 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2786 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2787}
2788
2789TEST(Matcher, OfClass) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002790 StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002791 ofClass(hasName("X")))));
2792
2793 EXPECT_TRUE(
2794 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2795 EXPECT_TRUE(
2796 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2797 Constructor));
2798 EXPECT_TRUE(
2799 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2800 Constructor));
2801}
2802
2803TEST(Matcher, VisitsTemplateInstantiations) {
2804 EXPECT_TRUE(matches(
2805 "class A { public: void x(); };"
2806 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002807 "void f() { B<A> b; b.y(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002808 callExpr(callee(cxxMethodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002809
2810 EXPECT_TRUE(matches(
2811 "class A { public: void x(); };"
2812 "class C {"
2813 " public:"
2814 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2815 "};"
2816 "void f() {"
2817 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002818 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00002819 recordDecl(hasName("C"), hasDescendant(callExpr(
2820 callee(cxxMethodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002821}
2822
Daniel Jasper1dad1832012-07-10 20:20:19 +00002823TEST(Matcher, HandlesNullQualTypes) {
2824 // FIXME: Add a Type matcher so we can replace uses of this
2825 // variable with Type(True())
2826 const TypeMatcher AnyType = anything();
2827
2828 // We don't really care whether this matcher succeeds; we're testing that
2829 // it completes without crashing.
2830 EXPECT_TRUE(matches(
2831 "struct A { };"
2832 "template <typename T>"
2833 "void f(T t) {"
2834 " T local_t(t /* this becomes a null QualType in the AST */);"
2835 "}"
2836 "void g() {"
2837 " f(0);"
2838 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002839 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002840 anyOf(
2841 TypeMatcher(hasDeclaration(anything())),
2842 pointsTo(AnyType),
2843 references(AnyType)
2844 // Other QualType matchers should go here.
2845 ))))));
2846}
2847
Manuel Klimek04616e42012-07-06 05:48:52 +00002848// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002849AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002850 // Make sure all special variables are used: node, match_finder,
2851 // bound_nodes_builder, and the parameter named 'AMatcher'.
2852 return AMatcher.matches(Node, Finder, Builder);
2853}
2854
2855TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002856 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002857
2858 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002859 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002860
2861 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002862 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002863
2864 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002865 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002866}
2867
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002868AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2869 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
2870 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002871 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002872 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002873 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2874 ASTMatchFinder::BK_First);
2875}
2876
2877TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002878 DeclarationMatcher HasClassB =
2879 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002880
2881 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002882 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002883
2884 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002885 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002886
2887 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002888 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002889
2890 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002891 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002892
2893 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2894}
2895
2896TEST(For, FindsForLoops) {
2897 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2898 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002899 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2900 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002901 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002902}
2903
Daniel Jasper4e566c42012-07-12 08:50:38 +00002904TEST(For, ForLoopInternals) {
2905 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2906 forStmt(hasCondition(anything()))));
2907 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2908 forStmt(hasLoopInit(anything()))));
2909}
2910
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002911TEST(For, ForRangeLoopInternals) {
2912 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002913 cxxForRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002914 EXPECT_TRUE(matches(
2915 "void f(){ int a[] {1, 2}; for (int i : a); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002916 cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002917}
2918
Daniel Jasper4e566c42012-07-12 08:50:38 +00002919TEST(For, NegativeForLoopInternals) {
2920 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002921 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002922 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2923 forStmt(hasLoopInit(anything()))));
2924}
2925
Manuel Klimek04616e42012-07-06 05:48:52 +00002926TEST(For, ReportsNoFalsePositives) {
2927 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2928 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2929}
2930
2931TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002932 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2933 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2934 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002935}
2936
2937TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2938 // It's not a compound statement just because there's "{}" in the source
2939 // text. This is an AST search, not grep.
2940 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002941 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002942 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002943 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002944}
2945
Daniel Jasper4e566c42012-07-12 08:50:38 +00002946TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002947 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002948 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002949 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002950 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002951 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002952 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002953 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002954 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002955 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002956 cxxForRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002957}
2958
2959TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2960 // The simplest case: every compound statement is in a function
2961 // definition, and the function body itself must be a compound
2962 // statement.
2963 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002964 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002965}
2966
2967TEST(HasAnySubstatement, IsNotRecursive) {
2968 // It's really "has any immediate substatement".
2969 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002970 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002971}
2972
2973TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2974 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002975 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002976}
2977
2978TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2979 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002980 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002981}
2982
2983TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2984 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002985 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002986 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002987 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002988}
2989
2990TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2991 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002992 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002993 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002994 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002995 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002996 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002997}
2998
2999TEST(StatementCountIs, WorksWithMultipleStatements) {
3000 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003001 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003002}
3003
3004TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
3005 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003006 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003007 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003008 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003009 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003010 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003011 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003012 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003013}
3014
3015TEST(Member, WorksInSimplestCase) {
3016 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003017 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003018}
3019
3020TEST(Member, DoesNotMatchTheBaseExpression) {
3021 // Don't pick out the wrong part of the member expression, this should
3022 // be checking the member (name) only.
3023 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003024 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003025}
3026
3027TEST(Member, MatchesInMemberFunctionCall) {
3028 EXPECT_TRUE(matches("void f() {"
3029 " struct { void first() {}; } s;"
3030 " s.first();"
3031 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003032 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003033}
3034
Daniel Jasperb0c7b612012-10-23 15:46:39 +00003035TEST(Member, MatchesMember) {
3036 EXPECT_TRUE(matches(
3037 "struct A { int i; }; void f() { A a; a.i = 2; }",
3038 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
3039 EXPECT_TRUE(notMatches(
3040 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
3041 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
3042}
3043
Daniel Jasper639522c2013-02-25 12:02:08 +00003044TEST(Member, UnderstandsAccess) {
3045 EXPECT_TRUE(matches(
3046 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
3047 EXPECT_TRUE(notMatches(
3048 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
3049 EXPECT_TRUE(notMatches(
3050 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
3051
3052 EXPECT_TRUE(notMatches(
3053 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
3054 EXPECT_TRUE(notMatches(
3055 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
3056 EXPECT_TRUE(matches(
3057 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
3058
3059 EXPECT_TRUE(notMatches(
3060 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
3061 EXPECT_TRUE(matches("class A { protected: int i; };",
3062 fieldDecl(isProtected(), hasName("i"))));
3063 EXPECT_TRUE(notMatches(
3064 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
3065
3066 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
3067 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
3068 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
3069 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
3070}
3071
Dmitri Gribenko06963042012-08-18 00:29:27 +00003072TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00003073 // Fails in C++11 mode
3074 EXPECT_TRUE(matchesConditionally(
3075 "namespace std { typedef typeof(sizeof(int)) size_t; }"
3076 "class X { void *operator new(std::size_t); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003077 cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00003078
3079 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003080 cxxMethodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00003081
Daniel Jasper5901e472012-10-01 13:40:41 +00003082 // Fails in C++11 mode
3083 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003084 "namespace std { typedef typeof(sizeof(int)) size_t; }"
3085 "class X { void operator delete[](void*, std::size_t); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003086 cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00003087}
3088
Manuel Klimek04616e42012-07-06 05:48:52 +00003089TEST(HasObjectExpression, DoesNotMatchMember) {
3090 EXPECT_TRUE(notMatches(
3091 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003092 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003093}
3094
3095TEST(HasObjectExpression, MatchesBaseOfVariable) {
3096 EXPECT_TRUE(matches(
3097 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003098 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003099 EXPECT_TRUE(matches(
3100 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003101 memberExpr(hasObjectExpression(
3102 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003103}
3104
3105TEST(HasObjectExpression,
3106 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
3107 EXPECT_TRUE(matches(
3108 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003109 memberExpr(hasObjectExpression(
3110 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003111 EXPECT_TRUE(matches(
3112 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003113 memberExpr(hasObjectExpression(
3114 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003115}
3116
3117TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003118 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
3119 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
3120 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
3121 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003122}
3123
3124TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003125 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003126}
3127
Aaron Ballman6290fc92015-11-23 17:09:24 +00003128TEST(IsVolatileQualified, QualifiersMatch) {
3129 EXPECT_TRUE(matches("volatile int i = 42;",
3130 varDecl(hasType(isVolatileQualified()))));
3131 EXPECT_TRUE(notMatches("volatile int *i;",
3132 varDecl(hasType(isVolatileQualified()))));
3133 EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
3134 varDecl(hasType(isVolatileQualified()))));
3135}
3136
Manuel Klimek04616e42012-07-06 05:48:52 +00003137TEST(IsConstQualified, MatchesConstInt) {
3138 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003139 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003140}
3141
3142TEST(IsConstQualified, MatchesConstPointer) {
3143 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003144 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003145}
3146
3147TEST(IsConstQualified, MatchesThroughTypedef) {
3148 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003149 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003150 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003151 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003152}
3153
3154TEST(IsConstQualified, DoesNotMatchInappropriately) {
3155 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003156 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003157 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003158 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003159}
3160
Sam Panzer80c13772012-08-16 16:58:10 +00003161TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003162 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
3163 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
3164 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
3165 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003166}
3167TEST(CastExpression, MatchesImplicitCasts) {
3168 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00003169 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003170 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00003171 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003172}
3173
3174TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003175 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
3176 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
3177 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
3178 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003179}
3180
Manuel Klimek04616e42012-07-06 05:48:52 +00003181TEST(ReinterpretCast, MatchesSimpleCase) {
3182 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003183 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003184}
3185
3186TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003187 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003188 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003189 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003190 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003191 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003192 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3193 "B b;"
3194 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003195 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003196}
3197
3198TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003199 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003200 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003201 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003202}
3203
3204TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003205 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003206 EXPECT_TRUE(
3207 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003208 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003209 EXPECT_TRUE(
3210 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003211 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003212}
3213
3214TEST(DynamicCast, MatchesSimpleCase) {
3215 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
3216 "B b;"
3217 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003218 cxxDynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003219}
3220
3221TEST(StaticCast, MatchesSimpleCase) {
3222 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Aaron Ballman512fb642015-09-17 13:30:52 +00003223 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003224}
3225
3226TEST(StaticCast, DoesNotMatchOtherCasts) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003227 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003228 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003229 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003230 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003231 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003232 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3233 "B b;"
3234 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003235 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003236}
3237
Daniel Jasper417f7762012-09-18 13:36:17 +00003238TEST(CStyleCast, MatchesSimpleCase) {
3239 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
3240}
3241
3242TEST(CStyleCast, DoesNotMatchOtherCasts) {
3243 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
3244 "char q, *r = const_cast<char*>(&q);"
3245 "void* s = reinterpret_cast<char*>(&s);"
3246 "struct B { virtual ~B() {} }; struct D : B {};"
3247 "B b;"
3248 "D* t = dynamic_cast<D*>(&b);",
3249 cStyleCastExpr()));
3250}
3251
Manuel Klimek04616e42012-07-06 05:48:52 +00003252TEST(HasDestinationType, MatchesSimpleCase) {
3253 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003254 cxxStaticCastExpr(hasDestinationType(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003255 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003256}
3257
Sam Panzer80c13772012-08-16 16:58:10 +00003258TEST(HasImplicitDestinationType, MatchesSimpleCase) {
3259 // This test creates an implicit const cast.
3260 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003261 implicitCastExpr(
3262 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003263 // This test creates an implicit array-to-pointer cast.
3264 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003265 implicitCastExpr(hasImplicitDestinationType(
3266 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003267}
3268
3269TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
3270 // This test creates an implicit cast from int to char.
3271 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003272 implicitCastExpr(hasImplicitDestinationType(
3273 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003274 // This test creates an implicit array-to-pointer cast.
3275 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003276 implicitCastExpr(hasImplicitDestinationType(
3277 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003278}
3279
3280TEST(ImplicitCast, MatchesSimpleCase) {
3281 // This test creates an implicit const cast.
3282 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003283 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003284 // This test creates an implicit cast from int to char.
3285 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003286 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003287 // This test creates an implicit array-to-pointer cast.
3288 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003289 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003290}
3291
3292TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003293 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00003294 // are present, and that it ignores explicit and paren casts.
3295
3296 // These two test cases have no casts.
3297 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003298 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003299 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003300 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003301
3302 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003303 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003304 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003305 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003306
3307 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003308 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003309}
3310
3311TEST(IgnoringImpCasts, MatchesImpCasts) {
3312 // This test checks that ignoringImpCasts matches when implicit casts are
3313 // present and its inner matcher alone does not match.
3314 // Note that this test creates an implicit const cast.
3315 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003316 varDecl(hasInitializer(ignoringImpCasts(
3317 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003318 // This test creates an implict cast from int to char.
3319 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003320 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003321 integerLiteral(equals(0)))))));
3322}
3323
3324TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3325 // These tests verify that ignoringImpCasts does not match if the inner
3326 // matcher does not match.
3327 // Note that the first test creates an implicit const cast.
3328 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003329 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003330 unless(anything()))))));
3331 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003332 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003333 unless(anything()))))));
3334
3335 // These tests verify that ignoringImplictCasts does not look through explicit
3336 // casts or parentheses.
3337 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003338 varDecl(hasInitializer(ignoringImpCasts(
3339 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003340 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003341 varDecl(hasInitializer(ignoringImpCasts(
3342 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003343 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003344 varDecl(hasInitializer(ignoringImpCasts(
3345 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003346 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003347 varDecl(hasInitializer(ignoringImpCasts(
3348 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003349}
3350
3351TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3352 // This test verifies that expressions that do not have implicit casts
3353 // still match the inner matcher.
3354 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003355 varDecl(hasInitializer(ignoringImpCasts(
3356 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003357}
3358
3359TEST(IgnoringParenCasts, MatchesParenCasts) {
3360 // This test checks that ignoringParenCasts matches when parentheses and/or
3361 // casts are present and its inner matcher alone does not match.
3362 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003363 varDecl(hasInitializer(ignoringParenCasts(
3364 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003365 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003366 varDecl(hasInitializer(ignoringParenCasts(
3367 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003368
3369 // This test creates an implict cast from int to char in addition to the
3370 // parentheses.
3371 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003372 varDecl(hasInitializer(ignoringParenCasts(
3373 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003374
3375 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003376 varDecl(hasInitializer(ignoringParenCasts(
3377 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003378 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003379 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003380 integerLiteral(equals(0)))))));
3381}
3382
3383TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3384 // This test verifies that expressions that do not have any casts still match.
3385 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003386 varDecl(hasInitializer(ignoringParenCasts(
3387 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003388}
3389
3390TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3391 // These tests verify that ignoringImpCasts does not match if the inner
3392 // matcher does not match.
3393 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003394 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003395 unless(anything()))))));
3396
3397 // This test creates an implicit cast from int to char in addition to the
3398 // parentheses.
3399 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003400 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003401 unless(anything()))))));
3402
3403 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003404 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003405 unless(anything()))))));
3406}
3407
3408TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3409 // This test checks that ignoringParenAndImpCasts matches when
3410 // parentheses and/or implicit casts are present and its inner matcher alone
3411 // does not match.
3412 // Note that this test creates an implicit const cast.
3413 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003414 varDecl(hasInitializer(ignoringParenImpCasts(
3415 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003416 // This test creates an implicit cast from int to char.
3417 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003418 varDecl(hasInitializer(ignoringParenImpCasts(
3419 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003420}
3421
3422TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3423 // This test verifies that expressions that do not have parentheses or
3424 // implicit casts still match.
3425 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003426 varDecl(hasInitializer(ignoringParenImpCasts(
3427 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003428 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003429 varDecl(hasInitializer(ignoringParenImpCasts(
3430 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003431}
3432
3433TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3434 // These tests verify that ignoringParenImpCasts does not match if
3435 // the inner matcher does not match.
3436 // This test creates an implicit cast.
3437 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003438 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003439 unless(anything()))))));
3440 // These tests verify that ignoringParenAndImplictCasts does not look
3441 // through explicit casts.
3442 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003443 varDecl(hasInitializer(ignoringParenImpCasts(
3444 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003445 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003446 varDecl(hasInitializer(ignoringParenImpCasts(
3447 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003448 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003449 varDecl(hasInitializer(ignoringParenImpCasts(
3450 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003451}
3452
Manuel Klimeke9235692012-07-25 10:02:02 +00003453TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003454 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3455 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003456 implicitCastExpr(
Aaron Ballman512fb642015-09-17 13:30:52 +00003457 hasSourceExpression(cxxConstructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003458}
3459
Manuel Klimeke9235692012-07-25 10:02:02 +00003460TEST(HasSourceExpression, MatchesExplicitCasts) {
3461 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003462 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003463 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003464 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003465}
3466
Manuel Klimek04616e42012-07-06 05:48:52 +00003467TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003468 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003469}
3470
3471TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003472 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003473}
3474
3475TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003476 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003477}
3478
3479TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003480 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003481}
3482
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003483TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3484 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3485 "const Foo f = Foo();",
3486 varDecl(hasInitializer(exprWithCleanups()))));
3487 EXPECT_FALSE(matches("struct Foo { };"
3488 "const Foo f = Foo();",
3489 varDecl(hasInitializer(exprWithCleanups()))));
3490}
3491
Daniel Jasper1dad1832012-07-10 20:20:19 +00003492TEST(InitListExpression, MatchesInitListExpression) {
3493 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3494 initListExpr(hasType(asString("int [2]")))));
3495 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003496 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003497 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3498 "void f();"
3499 "S s[1] = { &f };",
3500 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003501 EXPECT_TRUE(
3502 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003503}
3504
3505TEST(UsingDeclaration, MatchesUsingDeclarations) {
3506 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3507 usingDecl()));
3508}
3509
3510TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3511 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3512 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3513}
3514
3515TEST(UsingDeclaration, MatchesSpecificTarget) {
3516 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3517 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003518 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003519 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3520 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003521 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003522}
3523
3524TEST(UsingDeclaration, ThroughUsingDeclaration) {
3525 EXPECT_TRUE(matches(
3526 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003527 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003528 EXPECT_TRUE(notMatches(
3529 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003530 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003531}
3532
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003533TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3534 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3535 usingDirectiveDecl()));
3536 EXPECT_FALSE(
3537 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3538}
3539
Sam Panzerd624bfb2012-08-16 17:20:59 +00003540TEST(SingleDecl, IsSingleDecl) {
3541 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003542 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003543 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3544 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3545 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3546 SingleDeclStmt));
3547}
3548
3549TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003550 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003551
3552 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003553 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003554 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003555 declStmt(containsDeclaration(0, MatchesInit),
3556 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003557 unsigned WrongIndex = 42;
3558 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003559 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003560 MatchesInit))));
3561}
3562
3563TEST(DeclCount, DeclCountIsCorrect) {
3564 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003565 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003566 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003567 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003568 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003569 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003570}
3571
Manuel Klimek04616e42012-07-06 05:48:52 +00003572TEST(While, MatchesWhileLoops) {
3573 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3574 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3575 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3576}
3577
3578TEST(Do, MatchesDoLoops) {
3579 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3580 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3581}
3582
3583TEST(Do, DoesNotMatchWhileLoops) {
3584 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3585}
3586
3587TEST(SwitchCase, MatchesCase) {
3588 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3589 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3590 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3591 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3592}
3593
Daniel Jasper87c3d362012-09-20 14:12:57 +00003594TEST(SwitchCase, MatchesSwitch) {
3595 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3596 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3597 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3598 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3599}
3600
Peter Collingbourne3154a102013-05-10 11:52:02 +00003601TEST(SwitchCase, MatchesEachCase) {
3602 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3603 switchStmt(forEachSwitchCase(caseStmt()))));
3604 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3605 switchStmt(forEachSwitchCase(caseStmt()))));
3606 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3607 switchStmt(forEachSwitchCase(caseStmt()))));
3608 EXPECT_TRUE(notMatches(
3609 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3610 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3611 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3612 switchStmt(forEachSwitchCase(
3613 caseStmt(hasCaseConstant(integerLiteral()))))));
3614 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3615 switchStmt(forEachSwitchCase(
3616 caseStmt(hasCaseConstant(integerLiteral()))))));
3617 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3618 switchStmt(forEachSwitchCase(
3619 caseStmt(hasCaseConstant(integerLiteral()))))));
3620 EXPECT_TRUE(matchAndVerifyResultTrue(
3621 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3622 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3623 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3624}
3625
Manuel Klimekba46fc02013-07-19 11:50:54 +00003626TEST(ForEachConstructorInitializer, MatchesInitializers) {
3627 EXPECT_TRUE(matches(
3628 "struct X { X() : i(42), j(42) {} int i, j; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003629 cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer()))));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003630}
3631
Daniel Jasper87c3d362012-09-20 14:12:57 +00003632TEST(ExceptionHandling, SimpleCases) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003633 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
3634 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
3635 EXPECT_TRUE(
3636 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003637 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003638 cxxThrowExpr()));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003639 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003640 cxxThrowExpr()));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003641 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003642 cxxCatchStmt(isCatchAll())));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003643 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003644 cxxCatchStmt(isCatchAll())));
Aaron Ballman39918462015-07-15 17:11:21 +00003645 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3646 varDecl(isExceptionVariable())));
3647 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3648 varDecl(isExceptionVariable())));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003649}
3650
Manuel Klimek04616e42012-07-06 05:48:52 +00003651TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3652 EXPECT_TRUE(notMatches(
3653 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003654 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003655 EXPECT_TRUE(notMatches(
3656 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003657 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003658}
3659
3660TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3661 EXPECT_TRUE(matches(
3662 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003663 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003664}
3665
3666TEST(ForEach, BindsOneNode) {
3667 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003668 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003669 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003670}
3671
3672TEST(ForEach, BindsMultipleNodes) {
3673 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003674 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003675 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003676}
3677
3678TEST(ForEach, BindsRecursiveCombinations) {
3679 EXPECT_TRUE(matchAndVerifyResultTrue(
3680 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003681 recordDecl(hasName("C"),
3682 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003683 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003684}
3685
3686TEST(ForEachDescendant, BindsOneNode) {
3687 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003688 recordDecl(hasName("C"),
3689 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003690 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003691}
3692
Daniel Jasper94a56852012-11-16 18:39:22 +00003693TEST(ForEachDescendant, NestedForEachDescendant) {
3694 DeclarationMatcher m = recordDecl(
3695 isDefinition(), decl().bind("x"), hasName("C"));
3696 EXPECT_TRUE(matchAndVerifyResultTrue(
3697 "class A { class B { class C {}; }; };",
3698 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3699 new VerifyIdIsBoundTo<Decl>("x", "C")));
3700
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003701 // Check that a partial match of 'm' that binds 'x' in the
3702 // first part of anyOf(m, anything()) will not overwrite the
3703 // binding created by the earlier binding in the hasDescendant.
3704 EXPECT_TRUE(matchAndVerifyResultTrue(
3705 "class A { class B { class C {}; }; };",
3706 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3707 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003708}
3709
Manuel Klimek04616e42012-07-06 05:48:52 +00003710TEST(ForEachDescendant, BindsMultipleNodes) {
3711 EXPECT_TRUE(matchAndVerifyResultTrue(
3712 "class C { class D { int x; int y; }; "
3713 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003714 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003715 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003716}
3717
3718TEST(ForEachDescendant, BindsRecursiveCombinations) {
3719 EXPECT_TRUE(matchAndVerifyResultTrue(
3720 "class C { class D { "
3721 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003722 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3723 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003724 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003725}
3726
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003727TEST(ForEachDescendant, BindsCombinations) {
3728 EXPECT_TRUE(matchAndVerifyResultTrue(
3729 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3730 "(true) {} }",
3731 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3732 forEachDescendant(whileStmt().bind("while"))),
3733 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3734}
3735
3736TEST(Has, DoesNotDeleteBindings) {
3737 EXPECT_TRUE(matchAndVerifyResultTrue(
3738 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3739 new VerifyIdIsBoundTo<Decl>("x", 1)));
3740}
3741
3742TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3743 // Those matchers cover all the cases where an inner matcher is called
3744 // and there is not a 1:1 relationship between the match of the outer
3745 // matcher and the match of the inner matcher.
3746 // The pattern to look for is:
3747 // ... return InnerMatcher.matches(...); ...
3748 // In which case no special handling is needed.
3749 //
3750 // On the other hand, if there are multiple alternative matches
3751 // (for example forEach*) or matches might be discarded (for example has*)
3752 // the implementation must make sure that the discarded matches do not
3753 // affect the bindings.
3754 // When new such matchers are added, add a test here that:
3755 // - matches a simple node, and binds it as the first thing in the matcher:
3756 // recordDecl(decl().bind("x"), hasName("X")))
3757 // - uses the matcher under test afterwards in a way that not the first
3758 // alternative is matched; for anyOf, that means the first branch
3759 // would need to return false; for hasAncestor, it means that not
3760 // the direct parent matches the inner matcher.
3761
3762 EXPECT_TRUE(matchAndVerifyResultTrue(
3763 "class X { int y; };",
3764 recordDecl(
3765 recordDecl().bind("x"), hasName("::X"),
3766 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3767 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3768 EXPECT_TRUE(matchAndVerifyResultTrue(
3769 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3770 anyOf(unless(anything()), anything())),
3771 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3772 EXPECT_TRUE(matchAndVerifyResultTrue(
3773 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3774 classTemplateSpecializationDecl(
3775 decl().bind("x"),
3776 hasAnyTemplateArgument(refersToType(asString("int")))),
3777 new VerifyIdIsBoundTo<Decl>("x", 1)));
3778 EXPECT_TRUE(matchAndVerifyResultTrue(
3779 "class X { void f(); void g(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003780 cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003781 new VerifyIdIsBoundTo<Decl>("x", 1)));
3782 EXPECT_TRUE(matchAndVerifyResultTrue(
3783 "class X { X() : a(1), b(2) {} double a; int b; };",
3784 recordDecl(decl().bind("x"),
Aaron Ballman512fb642015-09-17 13:30:52 +00003785 has(cxxConstructorDecl(
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003786 hasAnyConstructorInitializer(forField(hasName("b")))))),
3787 new VerifyIdIsBoundTo<Decl>("x", 1)));
3788 EXPECT_TRUE(matchAndVerifyResultTrue(
3789 "void x(int, int) { x(0, 42); }",
3790 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3791 new VerifyIdIsBoundTo<Expr>("x", 1)));
3792 EXPECT_TRUE(matchAndVerifyResultTrue(
3793 "void x(int, int y) {}",
3794 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3795 new VerifyIdIsBoundTo<Decl>("x", 1)));
3796 EXPECT_TRUE(matchAndVerifyResultTrue(
3797 "void x() { return; if (true) {} }",
3798 functionDecl(decl().bind("x"),
3799 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3800 new VerifyIdIsBoundTo<Decl>("x", 1)));
3801 EXPECT_TRUE(matchAndVerifyResultTrue(
3802 "namespace X { void b(int); void b(); }"
3803 "using X::b;",
3804 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3805 functionDecl(parameterCountIs(1))))),
3806 new VerifyIdIsBoundTo<Decl>("x", 1)));
3807 EXPECT_TRUE(matchAndVerifyResultTrue(
3808 "class A{}; class B{}; class C : B, A {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003809 cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003810 new VerifyIdIsBoundTo<Decl>("x", 1)));
3811 EXPECT_TRUE(matchAndVerifyResultTrue(
3812 "class A{}; typedef A B; typedef A C; typedef A D;"
3813 "class E : A {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003814 cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003815 new VerifyIdIsBoundTo<Decl>("x", 1)));
3816 EXPECT_TRUE(matchAndVerifyResultTrue(
3817 "class A { class B { void f() {} }; };",
3818 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3819 new VerifyIdIsBoundTo<Decl>("x", 1)));
3820 EXPECT_TRUE(matchAndVerifyResultTrue(
3821 "template <typename T> struct A { struct B {"
3822 " void f() { if(true) {} }"
3823 "}; };"
3824 "void t() { A<int>::B b; b.f(); }",
3825 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3826 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3827 EXPECT_TRUE(matchAndVerifyResultTrue(
3828 "class A {};",
3829 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3830 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003831 EXPECT_TRUE(matchAndVerifyResultTrue(
3832 "class A { A() : s(), i(42) {} const char *s; int i; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003833 cxxConstructorDecl(hasName("::A::A"), decl().bind("x"),
3834 forEachConstructorInitializer(forField(hasName("i")))),
Manuel Klimekba46fc02013-07-19 11:50:54 +00003835 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003836}
3837
Daniel Jasper33806cd2012-11-11 22:14:55 +00003838TEST(ForEachDescendant, BindsCorrectNodes) {
3839 EXPECT_TRUE(matchAndVerifyResultTrue(
3840 "class C { void f(); int i; };",
3841 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3842 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3843 EXPECT_TRUE(matchAndVerifyResultTrue(
3844 "class C { void f() {} int i; };",
3845 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3846 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3847}
3848
Manuel Klimekabf43712013-02-04 10:59:20 +00003849TEST(FindAll, BindsNodeOnMatch) {
3850 EXPECT_TRUE(matchAndVerifyResultTrue(
3851 "class A {};",
3852 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3853 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3854}
3855
3856TEST(FindAll, BindsDescendantNodeOnMatch) {
3857 EXPECT_TRUE(matchAndVerifyResultTrue(
3858 "class A { int a; int b; };",
3859 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3860 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3861}
3862
3863TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3864 EXPECT_TRUE(matchAndVerifyResultTrue(
3865 "class A { int a; int b; };",
3866 recordDecl(hasName("::A"),
3867 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3868 fieldDecl().bind("v"))))),
3869 new VerifyIdIsBoundTo<Decl>("v", 3)));
3870
3871 EXPECT_TRUE(matchAndVerifyResultTrue(
3872 "class A { class B {}; class C {}; };",
3873 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3874 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3875}
3876
Manuel Klimek88b95872013-02-04 09:42:38 +00003877TEST(EachOf, TriggersForEachMatch) {
3878 EXPECT_TRUE(matchAndVerifyResultTrue(
3879 "class A { int a; int b; };",
3880 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3881 has(fieldDecl(hasName("b")).bind("v")))),
3882 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3883}
3884
3885TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3886 EXPECT_TRUE(matchAndVerifyResultTrue(
3887 "class A { int a; int c; };",
3888 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3889 has(fieldDecl(hasName("b")).bind("v")))),
3890 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3891 EXPECT_TRUE(matchAndVerifyResultTrue(
3892 "class A { int c; int b; };",
3893 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3894 has(fieldDecl(hasName("b")).bind("v")))),
3895 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3896 EXPECT_TRUE(notMatches(
3897 "class A { int c; int d; };",
3898 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3899 has(fieldDecl(hasName("b")).bind("v"))))));
3900}
Manuel Klimek04616e42012-07-06 05:48:52 +00003901
3902TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3903 // Make sure that we can both match the class by name (::X) and by the type
3904 // the template was instantiated with (via a field).
3905
3906 EXPECT_TRUE(matches(
3907 "template <typename T> class X {}; class A {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003908 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003909
3910 EXPECT_TRUE(matches(
3911 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003912 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003913 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003914}
3915
3916TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3917 EXPECT_TRUE(matches(
3918 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003919 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003920 isTemplateInstantiation())));
3921}
3922
3923TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3924 EXPECT_TRUE(matches(
3925 "template <typename T> class X { T t; }; class A {};"
3926 "template class X<A>;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003927 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003928 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003929}
3930
3931TEST(IsTemplateInstantiation,
3932 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3933 EXPECT_TRUE(matches(
3934 "template <typename T> class X {};"
3935 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003936 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003937}
3938
3939TEST(IsTemplateInstantiation,
3940 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3941 EXPECT_TRUE(matches(
3942 "class A {};"
3943 "class X {"
3944 " template <typename U> class Y { U u; };"
3945 " Y<A> y;"
3946 "};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003947 cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003948}
3949
3950TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3951 // FIXME: Figure out whether this makes sense. It doesn't affect the
3952 // normal use case as long as the uppermost instantiation always is marked
3953 // as template instantiation, but it might be confusing as a predicate.
3954 EXPECT_TRUE(matches(
3955 "class A {};"
3956 "template <typename T> class X {"
3957 " template <typename U> class Y { U u; };"
3958 " Y<T> y;"
3959 "}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003960 cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003961}
3962
3963TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3964 EXPECT_TRUE(notMatches(
3965 "template <typename T> class X {}; class A {};"
3966 "template <> class X<A> {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00003967 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003968}
3969
3970TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3971 EXPECT_TRUE(notMatches(
3972 "class A {}; class Y { A a; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003973 cxxRecordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003974}
3975
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003976TEST(IsInstantiated, MatchesInstantiation) {
3977 EXPECT_TRUE(
3978 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003979 cxxRecordDecl(isInstantiated())));
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003980}
3981
3982TEST(IsInstantiated, NotMatchesDefinition) {
3983 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003984 cxxRecordDecl(isInstantiated())));
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003985}
3986
3987TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3988 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3989 "class Y { A<int> a; }; Y y;",
3990 declStmt(isInTemplateInstantiation())));
3991}
3992
3993TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3994 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3995 declStmt(isInTemplateInstantiation())));
3996}
3997
3998TEST(IsInstantiated, MatchesFunctionInstantiation) {
3999 EXPECT_TRUE(
4000 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
4001 functionDecl(isInstantiated())));
4002}
4003
4004TEST(IsInstantiated, NotMatchesFunctionDefinition) {
4005 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
4006 varDecl(isInstantiated())));
4007}
4008
4009TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
4010 EXPECT_TRUE(
4011 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
4012 declStmt(isInTemplateInstantiation())));
4013}
4014
4015TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
4016 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
4017 declStmt(isInTemplateInstantiation())));
4018}
4019
4020TEST(IsInTemplateInstantiation, Sharing) {
4021 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
4022 // FIXME: Node sharing is an implementation detail, exposing it is ugly
4023 // and makes the matcher behave in non-obvious ways.
4024 EXPECT_TRUE(notMatches(
4025 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
4026 Matcher));
4027 EXPECT_TRUE(matches(
4028 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
4029 Matcher));
4030}
4031
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004032TEST(IsExplicitTemplateSpecialization,
4033 DoesNotMatchPrimaryTemplate) {
4034 EXPECT_TRUE(notMatches(
4035 "template <typename T> class X {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00004036 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004037 EXPECT_TRUE(notMatches(
4038 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004039 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004040}
4041
4042TEST(IsExplicitTemplateSpecialization,
4043 DoesNotMatchExplicitTemplateInstantiations) {
4044 EXPECT_TRUE(notMatches(
4045 "template <typename T> class X {};"
4046 "template class X<int>; extern template class X<long>;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004047 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004048 EXPECT_TRUE(notMatches(
4049 "template <typename T> void f(T t) {}"
4050 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004051 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004052}
4053
4054TEST(IsExplicitTemplateSpecialization,
4055 DoesNotMatchImplicitTemplateInstantiations) {
4056 EXPECT_TRUE(notMatches(
4057 "template <typename T> class X {}; X<int> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004058 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004059 EXPECT_TRUE(notMatches(
4060 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004061 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004062}
4063
4064TEST(IsExplicitTemplateSpecialization,
4065 MatchesExplicitTemplateSpecializations) {
4066 EXPECT_TRUE(matches(
4067 "template <typename T> class X {};"
4068 "template<> class X<int> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00004069 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004070 EXPECT_TRUE(matches(
4071 "template <typename T> void f(T t) {}"
4072 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004073 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004074}
4075
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004076TEST(HasAncenstor, MatchesDeclarationAncestors) {
4077 EXPECT_TRUE(matches(
4078 "class A { class B { class C {}; }; };",
4079 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
4080}
4081
4082TEST(HasAncenstor, FailsIfNoAncestorMatches) {
4083 EXPECT_TRUE(notMatches(
4084 "class A { class B { class C {}; }; };",
4085 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
4086}
4087
4088TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
4089 EXPECT_TRUE(matches(
4090 "class A { class B { void f() { C c; } class C {}; }; };",
4091 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
4092 hasAncestor(recordDecl(hasName("A"))))))));
4093}
4094
4095TEST(HasAncenstor, MatchesStatementAncestors) {
4096 EXPECT_TRUE(matches(
4097 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00004098 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004099}
4100
4101TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
4102 EXPECT_TRUE(matches(
4103 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00004104 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004105}
4106
4107TEST(HasAncestor, BindsRecursiveCombinations) {
4108 EXPECT_TRUE(matchAndVerifyResultTrue(
4109 "class C { class D { class E { class F { int y; }; }; }; };",
4110 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004111 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004112}
4113
4114TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
4115 EXPECT_TRUE(matchAndVerifyResultTrue(
4116 "class C { class D { class E { class F { int y; }; }; }; };",
4117 fieldDecl(hasAncestor(
4118 decl(
4119 hasDescendant(recordDecl(isDefinition(),
4120 hasAncestor(recordDecl())))
4121 ).bind("d")
4122 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004123 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004124}
4125
Manuel Klimekb64d6b72013-03-14 16:33:21 +00004126TEST(HasAncestor, MatchesClosestAncestor) {
4127 EXPECT_TRUE(matchAndVerifyResultTrue(
4128 "template <typename T> struct C {"
4129 " void f(int) {"
4130 " struct I { void g(T) { int x; } } i; i.g(42);"
4131 " }"
4132 "};"
4133 "template struct C<int>;",
4134 varDecl(hasName("x"),
4135 hasAncestor(functionDecl(hasParameter(
4136 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
4137 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
4138}
4139
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004140TEST(HasAncestor, MatchesInTemplateInstantiations) {
4141 EXPECT_TRUE(matches(
4142 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
4143 "A<int>::B::C a;",
4144 fieldDecl(hasType(asString("int")),
4145 hasAncestor(recordDecl(hasName("A"))))));
4146}
4147
4148TEST(HasAncestor, MatchesInImplicitCode) {
4149 EXPECT_TRUE(matches(
4150 "struct X {}; struct A { A() {} X x; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00004151 cxxConstructorDecl(
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004152 hasAnyConstructorInitializer(withInitializer(expr(
4153 hasAncestor(recordDecl(hasName("A")))))))));
4154}
4155
Daniel Jasper632aea92012-10-22 16:26:51 +00004156TEST(HasParent, MatchesOnlyParent) {
4157 EXPECT_TRUE(matches(
4158 "void f() { if (true) { int x = 42; } }",
4159 compoundStmt(hasParent(ifStmt()))));
4160 EXPECT_TRUE(notMatches(
4161 "void f() { for (;;) { int x = 42; } }",
4162 compoundStmt(hasParent(ifStmt()))));
4163 EXPECT_TRUE(notMatches(
4164 "void f() { if (true) for (;;) { int x = 42; } }",
4165 compoundStmt(hasParent(ifStmt()))));
4166}
4167
Manuel Klimekc844a462012-12-06 14:42:48 +00004168TEST(HasAncestor, MatchesAllAncestors) {
4169 EXPECT_TRUE(matches(
4170 "template <typename T> struct C { static void f() { 42; } };"
4171 "void t() { C<int>::f(); }",
4172 integerLiteral(
4173 equals(42),
Aaron Ballman512fb642015-09-17 13:30:52 +00004174 allOf(
4175 hasAncestor(cxxRecordDecl(isTemplateInstantiation())),
4176 hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation())))))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004177}
4178
4179TEST(HasParent, MatchesAllParents) {
4180 EXPECT_TRUE(matches(
4181 "template <typename T> struct C { static void f() { 42; } };"
4182 "void t() { C<int>::f(); }",
4183 integerLiteral(
4184 equals(42),
4185 hasParent(compoundStmt(hasParent(functionDecl(
Aaron Ballman512fb642015-09-17 13:30:52 +00004186 hasParent(cxxRecordDecl(isTemplateInstantiation())))))))));
4187 EXPECT_TRUE(
4188 matches("template <typename T> struct C { static void f() { 42; } };"
4189 "void t() { C<int>::f(); }",
4190 integerLiteral(
4191 equals(42),
4192 hasParent(compoundStmt(hasParent(functionDecl(hasParent(
4193 cxxRecordDecl(unless(isTemplateInstantiation()))))))))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004194 EXPECT_TRUE(matches(
4195 "template <typename T> struct C { static void f() { 42; } };"
4196 "void t() { C<int>::f(); }",
4197 integerLiteral(equals(42),
Aaron Ballman512fb642015-09-17 13:30:52 +00004198 hasParent(compoundStmt(
4199 allOf(hasParent(functionDecl(hasParent(
4200 cxxRecordDecl(isTemplateInstantiation())))),
4201 hasParent(functionDecl(hasParent(cxxRecordDecl(
4202 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00004203 EXPECT_TRUE(
4204 notMatches("template <typename T> struct C { static void f() {} };"
4205 "void t() { C<int>::f(); }",
4206 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004207}
4208
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00004209TEST(HasParent, NoDuplicateParents) {
4210 class HasDuplicateParents : public BoundNodesCallback {
4211 public:
4212 bool run(const BoundNodes *Nodes) override { return false; }
4213 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
4214 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
4215 std::set<const void *> Parents;
4216 for (const auto &Parent : Context->getParents(*Node)) {
4217 if (!Parents.insert(Parent.getMemoizationData()).second) {
4218 return true;
4219 }
4220 }
4221 return false;
4222 }
4223 };
4224 EXPECT_FALSE(matchAndVerifyResultTrue(
4225 "template <typename T> int Foo() { return 1 + 2; }\n"
4226 "int x = Foo<int>() + Foo<unsigned>();",
4227 stmt().bind("node"), new HasDuplicateParents()));
4228}
4229
Daniel Jasper516b02e2012-10-17 08:52:59 +00004230TEST(TypeMatching, MatchesTypes) {
4231 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
4232}
4233
Samuel Benzaquenbd3232a2015-12-22 20:06:40 +00004234TEST(TypeMatching, MatchesBool) {
4235 EXPECT_TRUE(matches("struct S { bool func(); };",
4236 cxxMethodDecl(returns(booleanType()))));
4237 EXPECT_TRUE(notMatches("struct S { void func(); };",
4238 cxxMethodDecl(returns(booleanType()))));
4239}
4240
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004241TEST(TypeMatching, MatchesVoid) {
Aaron Ballman512fb642015-09-17 13:30:52 +00004242 EXPECT_TRUE(matches("struct S { void func(); };",
4243 cxxMethodDecl(returns(voidType()))));
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004244}
4245
Daniel Jasper516b02e2012-10-17 08:52:59 +00004246TEST(TypeMatching, MatchesArrayTypes) {
4247 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
4248 EXPECT_TRUE(matches("int a[42];", arrayType()));
4249 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
4250
4251 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
4252 arrayType(hasElementType(builtinType()))));
4253
4254 EXPECT_TRUE(matches(
4255 "int const a[] = { 2, 3 };",
4256 qualType(arrayType(hasElementType(builtinType())))));
4257 EXPECT_TRUE(matches(
4258 "int const a[] = { 2, 3 };",
4259 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4260 EXPECT_TRUE(matches(
4261 "typedef const int T; T x[] = { 1, 2 };",
4262 qualType(isConstQualified(), arrayType())));
4263
4264 EXPECT_TRUE(notMatches(
4265 "int a[] = { 2, 3 };",
4266 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4267 EXPECT_TRUE(notMatches(
4268 "int a[] = { 2, 3 };",
4269 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
4270 EXPECT_TRUE(notMatches(
4271 "int const a[] = { 2, 3 };",
4272 qualType(arrayType(hasElementType(builtinType())),
4273 unless(isConstQualified()))));
4274
4275 EXPECT_TRUE(matches("int a[2];",
4276 constantArrayType(hasElementType(builtinType()))));
4277 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
4278}
4279
Matthias Gehre2cf7e802015-10-12 21:46:07 +00004280TEST(TypeMatching, DecayedType) {
4281 EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
4282 EXPECT_TRUE(notMatches("int i[7];", decayedType()));
4283}
4284
Daniel Jasper516b02e2012-10-17 08:52:59 +00004285TEST(TypeMatching, MatchesComplexTypes) {
4286 EXPECT_TRUE(matches("_Complex float f;", complexType()));
4287 EXPECT_TRUE(matches(
4288 "_Complex float f;",
4289 complexType(hasElementType(builtinType()))));
4290 EXPECT_TRUE(notMatches(
4291 "_Complex float f;",
4292 complexType(hasElementType(isInteger()))));
4293}
4294
4295TEST(TypeMatching, MatchesConstantArrayTypes) {
4296 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
4297 EXPECT_TRUE(notMatches(
4298 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
4299 constantArrayType(hasElementType(builtinType()))));
4300
4301 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
4302 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
4303 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
4304}
4305
4306TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
4307 EXPECT_TRUE(matches(
4308 "template <typename T, int Size> class array { T data[Size]; };",
4309 dependentSizedArrayType()));
4310 EXPECT_TRUE(notMatches(
4311 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
4312 dependentSizedArrayType()));
4313}
4314
4315TEST(TypeMatching, MatchesIncompleteArrayType) {
4316 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
4317 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
4318
4319 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
4320 incompleteArrayType()));
4321}
4322
4323TEST(TypeMatching, MatchesVariableArrayType) {
4324 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
4325 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4326
4327 EXPECT_TRUE(matches(
4328 "void f(int b) { int a[b]; }",
4329 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4330 varDecl(hasName("b")))))))));
4331}
4332
4333TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00004334 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4335 llvm::Triple::Win32) {
4336 // FIXME: Make this work for MSVC.
4337 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004338
David Majnemer197e2102014-03-05 06:32:38 +00004339 EXPECT_TRUE(matches("_Atomic(int) i;",
4340 atomicType(hasValueType(isInteger()))));
4341 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4342 atomicType(hasValueType(isInteger()))));
4343 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004344}
4345
4346TEST(TypeMatching, MatchesAutoTypes) {
4347 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4348 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4349 autoType()));
4350
Richard Smith061f1e22013-04-30 21:23:01 +00004351 // FIXME: Matching against the type-as-written can't work here, because the
4352 // type as written was not deduced.
4353 //EXPECT_TRUE(matches("auto a = 1;",
4354 // autoType(hasDeducedType(isInteger()))));
4355 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4356 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004357}
4358
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004359TEST(TypeMatching, MatchesFunctionTypes) {
4360 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4361 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4362}
4363
Edwin Vaneec074802013-04-01 18:33:34 +00004364TEST(TypeMatching, MatchesParenType) {
4365 EXPECT_TRUE(
4366 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4367 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4368
4369 EXPECT_TRUE(matches(
4370 "int (*ptr_to_func)(int);",
4371 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4372 EXPECT_TRUE(notMatches(
4373 "int (*ptr_to_array)[4];",
4374 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4375}
4376
Daniel Jasper516b02e2012-10-17 08:52:59 +00004377TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004378 // FIXME: Reactive when these tests can be more specific (not matching
4379 // implicit code on certain platforms), likely when we have hasDescendant for
4380 // Types/TypeLocs.
4381 //EXPECT_TRUE(matchAndVerifyResultTrue(
4382 // "int* a;",
4383 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4384 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4385 //EXPECT_TRUE(matchAndVerifyResultTrue(
4386 // "int* a;",
4387 // pointerTypeLoc().bind("loc"),
4388 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004389 EXPECT_TRUE(matches(
4390 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004391 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004392 EXPECT_TRUE(matches(
4393 "int** a;",
4394 loc(pointerType(pointee(pointerType())))));
4395 EXPECT_TRUE(matches(
4396 "int* b; int* * const a = &b;",
4397 loc(qualType(isConstQualified(), pointerType()))));
4398
4399 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004400 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4401 hasType(blockPointerType()))));
4402 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4403 hasType(memberPointerType()))));
4404 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4405 hasType(pointerType()))));
4406 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4407 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004408 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4409 hasType(lValueReferenceType()))));
4410 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4411 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004412
Daniel Jasper7943eb52012-10-17 13:35:36 +00004413 Fragment = "int *ptr;";
4414 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4415 hasType(blockPointerType()))));
4416 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4417 hasType(memberPointerType()))));
4418 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4419 hasType(pointerType()))));
4420 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4421 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004422
Daniel Jasper7943eb52012-10-17 13:35:36 +00004423 Fragment = "int a; int &ref = a;";
4424 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4425 hasType(blockPointerType()))));
4426 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4427 hasType(memberPointerType()))));
4428 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4429 hasType(pointerType()))));
4430 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4431 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004432 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4433 hasType(lValueReferenceType()))));
4434 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4435 hasType(rValueReferenceType()))));
4436
4437 Fragment = "int &&ref = 2;";
4438 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4439 hasType(blockPointerType()))));
4440 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4441 hasType(memberPointerType()))));
4442 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4443 hasType(pointerType()))));
4444 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4445 hasType(referenceType()))));
4446 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4447 hasType(lValueReferenceType()))));
4448 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4449 hasType(rValueReferenceType()))));
4450}
4451
4452TEST(TypeMatching, AutoRefTypes) {
4453 std::string Fragment = "auto a = 1;"
4454 "auto b = a;"
4455 "auto &c = a;"
4456 "auto &&d = c;"
4457 "auto &&e = 2;";
4458 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4459 hasType(referenceType()))));
4460 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4461 hasType(referenceType()))));
4462 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4463 hasType(referenceType()))));
4464 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4465 hasType(lValueReferenceType()))));
4466 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4467 hasType(rValueReferenceType()))));
4468 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4469 hasType(referenceType()))));
4470 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4471 hasType(lValueReferenceType()))));
4472 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4473 hasType(rValueReferenceType()))));
4474 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4475 hasType(referenceType()))));
4476 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4477 hasType(lValueReferenceType()))));
4478 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4479 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004480}
4481
4482TEST(TypeMatching, PointeeTypes) {
4483 EXPECT_TRUE(matches("int b; int &a = b;",
4484 referenceType(pointee(builtinType()))));
4485 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4486
4487 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004488 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004489
4490 EXPECT_TRUE(matches(
4491 "int const *A;",
4492 pointerType(pointee(isConstQualified(), builtinType()))));
4493 EXPECT_TRUE(notMatches(
4494 "int *A;",
4495 pointerType(pointee(isConstQualified(), builtinType()))));
4496}
4497
4498TEST(TypeMatching, MatchesPointersToConstTypes) {
4499 EXPECT_TRUE(matches("int b; int * const a = &b;",
4500 loc(pointerType())));
4501 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004502 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004503 EXPECT_TRUE(matches(
4504 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004505 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004506 EXPECT_TRUE(matches(
4507 "int b; const int * a = &b;",
4508 pointerType(pointee(builtinType()))));
4509}
4510
4511TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004512 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4513 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004514}
4515
Edwin Vanef901b712013-02-25 14:49:29 +00004516TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004517 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004518 templateSpecializationType()));
4519}
4520
Edwin Vaneb6eae142013-02-25 20:43:32 +00004521TEST(TypeMatching, MatchesRecordType) {
4522 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004523 EXPECT_TRUE(matches("struct S{}; S s;",
4524 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4525 EXPECT_TRUE(notMatches("int i;",
4526 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004527}
4528
4529TEST(TypeMatching, MatchesElaboratedType) {
4530 EXPECT_TRUE(matches(
4531 "namespace N {"
4532 " namespace M {"
4533 " class D {};"
4534 " }"
4535 "}"
4536 "N::M::D d;", elaboratedType()));
4537 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4538 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4539}
4540
4541TEST(ElaboratedTypeNarrowing, hasQualifier) {
4542 EXPECT_TRUE(matches(
4543 "namespace N {"
4544 " namespace M {"
4545 " class D {};"
4546 " }"
4547 "}"
4548 "N::M::D d;",
4549 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4550 EXPECT_TRUE(notMatches(
4551 "namespace M {"
4552 " class D {};"
4553 "}"
4554 "M::D d;",
4555 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004556 EXPECT_TRUE(notMatches(
4557 "struct D {"
4558 "} d;",
4559 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004560}
4561
4562TEST(ElaboratedTypeNarrowing, namesType) {
4563 EXPECT_TRUE(matches(
4564 "namespace N {"
4565 " namespace M {"
4566 " class D {};"
4567 " }"
4568 "}"
4569 "N::M::D d;",
4570 elaboratedType(elaboratedType(namesType(recordType(
4571 hasDeclaration(namedDecl(hasName("D")))))))));
4572 EXPECT_TRUE(notMatches(
4573 "namespace M {"
4574 " class D {};"
4575 "}"
4576 "M::D d;",
4577 elaboratedType(elaboratedType(namesType(typedefType())))));
4578}
4579
Samuel Benzaquenf8ec4542015-08-26 16:15:59 +00004580TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
4581 const std::string code = "template <typename T>"
4582 "int F() {"
4583 " return 1 + T();"
4584 "}"
4585 "int i = F<int>();";
4586 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
4587 expr(hasType(substTemplateTypeParmType()))))));
4588 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
4589 expr(hasType(substTemplateTypeParmType()))))));
4590}
4591
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004592TEST(NNS, MatchesNestedNameSpecifiers) {
4593 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4594 nestedNameSpecifier()));
4595 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4596 nestedNameSpecifier()));
4597 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4598 nestedNameSpecifier()));
Daniel Jasperc8f472c2015-12-02 13:57:46 +00004599 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
4600 nestedNameSpecifier()));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004601
4602 EXPECT_TRUE(matches(
4603 "struct A { static void f() {} }; void g() { A::f(); }",
4604 nestedNameSpecifier()));
4605 EXPECT_TRUE(notMatches(
4606 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4607 nestedNameSpecifier()));
4608}
4609
Daniel Jasper87c3d362012-09-20 14:12:57 +00004610TEST(NullStatement, SimpleCases) {
4611 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4612 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4613}
4614
Aaron Ballman11825f22015-08-18 19:55:20 +00004615TEST(NS, Anonymous) {
4616 EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
4617 EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
4618}
4619
Aaron Ballman6c79f352015-08-28 19:39:21 +00004620TEST(NS, Alias) {
4621 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
4622 namespaceAliasDecl(hasName("alias"))));
4623}
4624
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004625TEST(NNS, MatchesTypes) {
4626 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4627 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4628 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4629 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4630 Matcher));
4631 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4632}
4633
4634TEST(NNS, MatchesNamespaceDecls) {
4635 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4636 specifiesNamespace(hasName("ns")));
4637 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4638 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4639 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4640}
4641
4642TEST(NNS, BindsNestedNameSpecifiers) {
4643 EXPECT_TRUE(matchAndVerifyResultTrue(
4644 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4645 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4646 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4647}
4648
4649TEST(NNS, BindsNestedNameSpecifierLocs) {
4650 EXPECT_TRUE(matchAndVerifyResultTrue(
4651 "namespace ns { struct B {}; } ns::B b;",
4652 loc(nestedNameSpecifier()).bind("loc"),
4653 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4654}
4655
4656TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4657 EXPECT_TRUE(matches(
4658 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4659 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4660 EXPECT_TRUE(matches(
4661 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004662 nestedNameSpecifierLoc(hasPrefix(
4663 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004664}
4665
Daniel Jasper6fc34332012-10-30 15:42:00 +00004666TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4667 std::string Fragment =
4668 "namespace a { struct A { struct B { struct C {}; }; }; };"
4669 "void f() { a::A::B::C c; }";
4670 EXPECT_TRUE(matches(
4671 Fragment,
4672 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4673 hasDescendant(nestedNameSpecifier(
4674 specifiesNamespace(hasName("a")))))));
4675 EXPECT_TRUE(notMatches(
4676 Fragment,
4677 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4678 has(nestedNameSpecifier(
4679 specifiesNamespace(hasName("a")))))));
4680 EXPECT_TRUE(matches(
4681 Fragment,
4682 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4683 has(nestedNameSpecifier(
4684 specifiesNamespace(hasName("a")))))));
4685
4686 // Not really useful because a NestedNameSpecifier can af at most one child,
4687 // but to complete the interface.
4688 EXPECT_TRUE(matchAndVerifyResultTrue(
4689 Fragment,
4690 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4691 forEach(nestedNameSpecifier().bind("x"))),
4692 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4693}
4694
4695TEST(NNS, NestedNameSpecifiersAsDescendants) {
4696 std::string Fragment =
4697 "namespace a { struct A { struct B { struct C {}; }; }; };"
4698 "void f() { a::A::B::C c; }";
4699 EXPECT_TRUE(matches(
4700 Fragment,
4701 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4702 asString("struct a::A")))))));
4703 EXPECT_TRUE(matchAndVerifyResultTrue(
4704 Fragment,
4705 functionDecl(hasName("f"),
4706 forEachDescendant(nestedNameSpecifier().bind("x"))),
4707 // Nested names: a, a::A and a::A::B.
4708 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4709}
4710
4711TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4712 std::string Fragment =
4713 "namespace a { struct A { struct B { struct C {}; }; }; };"
4714 "void f() { a::A::B::C c; }";
4715 EXPECT_TRUE(matches(
4716 Fragment,
4717 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4718 hasDescendant(loc(nestedNameSpecifier(
4719 specifiesNamespace(hasName("a"))))))));
4720 EXPECT_TRUE(notMatches(
4721 Fragment,
4722 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4723 has(loc(nestedNameSpecifier(
4724 specifiesNamespace(hasName("a"))))))));
4725 EXPECT_TRUE(matches(
4726 Fragment,
4727 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4728 has(loc(nestedNameSpecifier(
4729 specifiesNamespace(hasName("a"))))))));
4730
4731 EXPECT_TRUE(matchAndVerifyResultTrue(
4732 Fragment,
4733 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4734 forEach(nestedNameSpecifierLoc().bind("x"))),
4735 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4736}
4737
4738TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4739 std::string Fragment =
4740 "namespace a { struct A { struct B { struct C {}; }; }; };"
4741 "void f() { a::A::B::C c; }";
4742 EXPECT_TRUE(matches(
4743 Fragment,
4744 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4745 asString("struct a::A"))))))));
4746 EXPECT_TRUE(matchAndVerifyResultTrue(
4747 Fragment,
4748 functionDecl(hasName("f"),
4749 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4750 // Nested names: a, a::A and a::A::B.
4751 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4752}
4753
Manuel Klimek191c0932013-02-01 13:41:35 +00004754template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004755public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004756 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4757 StringRef InnerId)
4758 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004759 }
4760
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004761 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004762
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004763 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004764 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004765 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4766 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004767 }
4768private:
4769 std::string Id;
4770 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004771 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004772};
4773
4774TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004775 EXPECT_TRUE(matchAndVerifyResultTrue(
4776 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4777 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004778 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4779 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004780 EXPECT_TRUE(matchAndVerifyResultFalse(
4781 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4782 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004783 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4784 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004785}
4786
4787TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004788 EXPECT_TRUE(matchAndVerifyResultTrue(
4789 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004790 new VerifyMatchOnNode<clang::Stmt>(
4791 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004792 EXPECT_TRUE(matchAndVerifyResultFalse(
4793 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004794 new VerifyMatchOnNode<clang::Stmt>(
4795 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004796}
4797
4798TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4799 EXPECT_TRUE(matchAndVerifyResultTrue(
4800 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4801 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004802 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004803 EXPECT_TRUE(matchAndVerifyResultFalse(
4804 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4805 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004806 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004807}
4808
Manuel Klimekbee08572013-02-07 12:42:10 +00004809template <typename T>
4810class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4811public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004812 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00004813
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004814 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00004815 const T *Node = Nodes->getNodeAs<T>("");
4816 return verify(*Nodes, *Context, Node);
4817 }
4818
4819 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004820 // Use the original typed pointer to verify we can pass pointers to subtypes
4821 // to equalsNode.
4822 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004823 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004824 "", match(stmt(hasParent(
4825 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004826 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004827 }
4828 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004829 // Use the original typed pointer to verify we can pass pointers to subtypes
4830 // to equalsNode.
4831 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004832 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004833 "", match(decl(hasParent(
4834 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004835 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004836 }
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00004837 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
4838 // Use the original typed pointer to verify we can pass pointers to subtypes
4839 // to equalsNode.
4840 const T *TypedNode = cast<T>(Node);
4841 const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
4842 return selectFirst<T>(
4843 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
4844 hasType(type(equalsNode(TypedNode)).bind(""))))))),
4845 *Dec, Context)) != nullptr;
4846 }
Manuel Klimekbee08572013-02-07 12:42:10 +00004847};
4848
4849TEST(IsEqualTo, MatchesNodesByIdentity) {
4850 EXPECT_TRUE(matchAndVerifyResultTrue(
4851 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004852 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4853 EXPECT_TRUE(matchAndVerifyResultTrue(
4854 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4855 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00004856 EXPECT_TRUE(matchAndVerifyResultTrue(
4857 "class X { class Y {} y; };",
4858 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
4859 new VerifyAncestorHasChildIsEqual<Type>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004860}
4861
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004862TEST(MatchFinder, CheckProfiling) {
4863 MatchFinder::MatchFinderOptions Options;
4864 llvm::StringMap<llvm::TimeRecord> Records;
4865 Options.CheckProfiling.emplace(Records);
4866 MatchFinder Finder(std::move(Options));
4867
4868 struct NamedCallback : public MatchFinder::MatchCallback {
4869 void run(const MatchFinder::MatchResult &Result) override {}
4870 StringRef getID() const override { return "MyID"; }
4871 } Callback;
4872 Finder.addMatcher(decl(), &Callback);
4873 std::unique_ptr<FrontendActionFactory> Factory(
4874 newFrontendActionFactory(&Finder));
4875 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4876
4877 EXPECT_EQ(1u, Records.size());
4878 EXPECT_EQ("MyID", Records.begin()->getKey());
4879}
4880
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004881class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4882public:
4883 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004884 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004885 EXPECT_TRUE(Called);
4886 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004887 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004888 bool Called;
4889};
4890
4891TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4892 MatchFinder Finder;
4893 VerifyStartOfTranslationUnit VerifyCallback;
4894 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004895 std::unique_ptr<FrontendActionFactory> Factory(
4896 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004897 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4898 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004899
4900 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004901 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004902 ASSERT_TRUE(AST.get());
4903 Finder.matchAST(AST->getASTContext());
4904 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004905}
4906
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004907class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4908public:
4909 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004910 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004911 EXPECT_FALSE(Called);
4912 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004913 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004914 bool Called;
4915};
4916
4917TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4918 MatchFinder Finder;
4919 VerifyEndOfTranslationUnit VerifyCallback;
4920 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004921 std::unique_ptr<FrontendActionFactory> Factory(
4922 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004923 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4924 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004925
4926 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004927 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004928 ASSERT_TRUE(AST.get());
4929 Finder.matchAST(AST->getASTContext());
4930 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004931}
4932
Manuel Klimekbbb75852013-06-20 14:06:32 +00004933TEST(EqualsBoundNodeMatcher, QualType) {
4934 EXPECT_TRUE(matches(
4935 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4936 hasInitializer(ignoringParenImpCasts(
4937 hasType(qualType(equalsBoundNode("type"))))))));
4938 EXPECT_TRUE(notMatches("int i = 1.f;",
4939 varDecl(hasType(qualType().bind("type")),
4940 hasInitializer(ignoringParenImpCasts(hasType(
4941 qualType(equalsBoundNode("type"))))))));
4942}
4943
4944TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4945 EXPECT_TRUE(notMatches(
4946 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4947 hasInitializer(ignoringParenImpCasts(
4948 hasType(qualType(equalsBoundNode("type"))))))));
4949}
4950
4951TEST(EqualsBoundNodeMatcher, Stmt) {
4952 EXPECT_TRUE(
4953 matches("void f() { if(true) {} }",
4954 stmt(allOf(ifStmt().bind("if"),
4955 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4956
4957 EXPECT_TRUE(notMatches(
4958 "void f() { if(true) { if (true) {} } }",
4959 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4960}
4961
4962TEST(EqualsBoundNodeMatcher, Decl) {
4963 EXPECT_TRUE(matches(
4964 "class X { class Y {}; };",
4965 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4966 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4967
4968 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4969 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4970 has(decl(equalsBoundNode("record")))))));
4971}
4972
4973TEST(EqualsBoundNodeMatcher, Type) {
4974 EXPECT_TRUE(matches(
4975 "class X { int a; int b; };",
4976 recordDecl(
4977 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4978 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4979
4980 EXPECT_TRUE(notMatches(
4981 "class X { int a; double b; };",
4982 recordDecl(
4983 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4984 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4985}
4986
4987TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004988 EXPECT_TRUE(matchAndVerifyResultTrue(
4989 "int f() {"
4990 " if (1) {"
4991 " int i = 9;"
4992 " }"
4993 " int j = 10;"
4994 " {"
4995 " float k = 9.0;"
4996 " }"
4997 " return 0;"
4998 "}",
4999 // Look for variable declarations within functions whose type is the same
5000 // as the function return type.
5001 functionDecl(returns(qualType().bind("type")),
5002 forEachDescendant(varDecl(hasType(
5003 qualType(equalsBoundNode("type")))).bind("decl"))),
5004 // Only i and j should match, not k.
5005 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
5006}
5007
5008TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
5009 EXPECT_TRUE(matchAndVerifyResultTrue(
5010 "void f() {"
5011 " int x;"
5012 " double d;"
5013 " x = d + x - d + x;"
5014 "}",
5015 functionDecl(
5016 hasName("f"), forEachDescendant(varDecl().bind("d")),
5017 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
5018 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
5019}
5020
Manuel Klimekce68f772014-03-25 14:39:26 +00005021TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
5022 EXPECT_TRUE(matchAndVerifyResultTrue(
5023 "struct StringRef { int size() const; const char* data() const; };"
5024 "void f(StringRef v) {"
5025 " v.data();"
5026 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00005027 cxxMemberCallExpr(
5028 callee(cxxMethodDecl(hasName("data"))),
5029 on(declRefExpr(to(
5030 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
5031 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
5032 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
Manuel Klimekce68f772014-03-25 14:39:26 +00005033 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
5034 .bind("data"),
5035 new VerifyIdIsBoundTo<Expr>("data", 1)));
5036
5037 EXPECT_FALSE(matches(
5038 "struct StringRef { int size() const; const char* data() const; };"
5039 "void f(StringRef v) {"
5040 " v.data();"
5041 " v.size();"
5042 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00005043 cxxMemberCallExpr(
5044 callee(cxxMethodDecl(hasName("data"))),
5045 on(declRefExpr(to(
5046 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
5047 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
5048 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
Manuel Klimekce68f772014-03-25 14:39:26 +00005049 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
5050 .bind("data")));
5051}
5052
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00005053TEST(TypeDefDeclMatcher, Match) {
5054 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
5055 typedefDecl(hasName("typedefDeclTest"))));
5056}
5057
Aaron Ballman11825f22015-08-18 19:55:20 +00005058TEST(IsInlineMatcher, IsInline) {
5059 EXPECT_TRUE(matches("void g(); inline void f();",
5060 functionDecl(isInline(), hasName("f"))));
5061 EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
5062 namespaceDecl(isInline(), hasName("m"))));
5063}
5064
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00005065// FIXME: Figure out how to specify paths so the following tests pass on Windows.
5066#ifndef LLVM_ON_WIN32
5067
5068TEST(Matcher, IsExpansionInMainFileMatcher) {
5069 EXPECT_TRUE(matches("class X {};",
5070 recordDecl(hasName("X"), isExpansionInMainFile())));
5071 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
5072 FileContentMappings M;
5073 M.push_back(std::make_pair("/other", "class X {};"));
5074 EXPECT_TRUE(matchesConditionally("#include <other>\n",
5075 recordDecl(isExpansionInMainFile()), false,
5076 "-isystem/", M));
5077}
5078
5079TEST(Matcher, IsExpansionInSystemHeader) {
5080 FileContentMappings M;
5081 M.push_back(std::make_pair("/other", "class X {};"));
5082 EXPECT_TRUE(matchesConditionally(
5083 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
5084 "-isystem/", M));
5085 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
5086 recordDecl(isExpansionInSystemHeader()),
5087 false, "-I/", M));
5088 EXPECT_TRUE(notMatches("class X {};",
5089 recordDecl(isExpansionInSystemHeader())));
5090 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
5091}
5092
5093TEST(Matcher, IsExpansionInFileMatching) {
5094 FileContentMappings M;
5095 M.push_back(std::make_pair("/foo", "class A {};"));
5096 M.push_back(std::make_pair("/bar", "class B {};"));
5097 EXPECT_TRUE(matchesConditionally(
5098 "#include <foo>\n"
5099 "#include <bar>\n"
5100 "class X {};",
5101 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
5102 "-isystem/", M));
5103 EXPECT_TRUE(matchesConditionally(
5104 "#include <foo>\n"
5105 "#include <bar>\n"
5106 "class X {};",
5107 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
5108 "-isystem/", M));
5109}
5110
5111#endif // LLVM_ON_WIN32
5112
Manuel Klimekbfa43572015-03-12 15:48:15 +00005113
5114TEST(ObjCMessageExprMatcher, SimpleExprs) {
5115 // don't find ObjCMessageExpr where none are present
5116 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
5117
5118 std::string Objc1String =
5119 "@interface Str "
5120 " - (Str *)uppercaseString:(Str *)str;"
5121 "@end "
5122 "@interface foo "
5123 "- (void)meth:(Str *)text;"
5124 "@end "
5125 " "
5126 "@implementation foo "
5127 "- (void) meth:(Str *)text { "
5128 " [self contents];"
5129 " Str *up = [text uppercaseString];"
5130 "} "
5131 "@end ";
5132 EXPECT_TRUE(matchesObjC(
5133 Objc1String,
5134 objcMessageExpr(anything())));
5135 EXPECT_TRUE(matchesObjC(
5136 Objc1String,
5137 objcMessageExpr(hasSelector("contents"))));
5138 EXPECT_TRUE(matchesObjC(
5139 Objc1String,
5140 objcMessageExpr(matchesSelector("cont*"))));
5141 EXPECT_FALSE(matchesObjC(
5142 Objc1String,
5143 objcMessageExpr(matchesSelector("?cont*"))));
5144 EXPECT_TRUE(notMatchesObjC(
5145 Objc1String,
5146 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
5147 EXPECT_TRUE(matchesObjC(
5148 Objc1String,
5149 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
5150 EXPECT_TRUE(matchesObjC(
5151 Objc1String,
Manuel Klimeke67a9d62015-09-08 10:11:26 +00005152 objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
5153 EXPECT_TRUE(matchesObjC(
5154 Objc1String,
Manuel Klimekbfa43572015-03-12 15:48:15 +00005155 objcMessageExpr(matchesSelector("uppercase*"),
5156 argumentCountIs(0)
5157 )));
5158
5159}
5160
Manuel Klimek04616e42012-07-06 05:48:52 +00005161} // end namespace ast_matchers
5162} // end namespace clang