blob: a777e7f497cff38408e00ad43a4e5bf9ec8a28e1 [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
Aaron Ballman7e7b7b22016-02-01 14:11:47 +00001094TEST(HasType, MatchesTypedefDecl) {
1095 EXPECT_TRUE(matches("typedef int X;", typedefDecl(hasType(asString("int")))));
1096 EXPECT_TRUE(matches("typedef const int T;",
1097 typedefDecl(hasType(asString("const int")))));
1098 EXPECT_TRUE(notMatches("typedef const int T;",
1099 typedefDecl(hasType(asString("int")))));
1100 EXPECT_TRUE(matches("typedef int foo; typedef foo bar;",
1101 typedefDecl(hasType(asString("foo")), hasName("bar"))));
1102}
1103
Manuel Klimekc16c6522013-06-20 13:08:29 +00001104TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1105 EXPECT_TRUE(matches("int x;",
1106 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1107
1108 // Make sure we don't crash on implicit constructors.
1109 EXPECT_TRUE(notMatches("class X {}; X x;",
1110 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1111}
1112
Manuel Klimek04616e42012-07-06 05:48:52 +00001113TEST(Matcher, Call) {
1114 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001115 // Matcher<Decl>, too?
Aaron Ballman512fb642015-09-17 13:30:52 +00001116 StatementMatcher MethodX =
1117 callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001118
1119 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1120 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1121
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001122 StatementMatcher MethodOnY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001123 cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001124
1125 EXPECT_TRUE(
1126 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1127 MethodOnY));
1128 EXPECT_TRUE(
1129 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1130 MethodOnY));
1131 EXPECT_TRUE(
1132 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1133 MethodOnY));
1134 EXPECT_TRUE(
1135 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1136 MethodOnY));
1137 EXPECT_TRUE(
1138 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1139 MethodOnY));
1140
1141 StatementMatcher MethodOnYPointer =
Aaron Ballman512fb642015-09-17 13:30:52 +00001142 cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001143
1144 EXPECT_TRUE(
1145 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1146 MethodOnYPointer));
1147 EXPECT_TRUE(
1148 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1149 MethodOnYPointer));
1150 EXPECT_TRUE(
1151 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1152 MethodOnYPointer));
1153 EXPECT_TRUE(
1154 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1155 MethodOnYPointer));
1156 EXPECT_TRUE(
1157 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1158 MethodOnYPointer));
1159}
1160
Daniel Jasper5901e472012-10-01 13:40:41 +00001161TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001162 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001163 lambdaExpr()));
1164}
1165
1166TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001167 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1168 "void f() { for (auto &a : as); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001169 cxxForRangeStmt()));
Daniel Jasper5901e472012-10-01 13:40:41 +00001170 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001171 cxxForRangeStmt()));
Daniel Jasper5901e472012-10-01 13:40:41 +00001172}
1173
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001174TEST(Matcher, SubstNonTypeTemplateParm) {
1175 EXPECT_FALSE(matches("template<int N>\n"
1176 "struct A { static const int n = 0; };\n"
1177 "struct B : public A<42> {};",
1178 substNonTypeTemplateParmExpr()));
1179 EXPECT_TRUE(matches("template<int N>\n"
1180 "struct A { static const int n = N; };\n"
1181 "struct B : public A<42> {};",
1182 substNonTypeTemplateParmExpr()));
1183}
1184
Aaron Ballman478a8eb2015-10-05 19:44:42 +00001185TEST(Matcher, NonTypeTemplateParmDecl) {
1186 EXPECT_TRUE(matches("template <int N> void f();",
1187 nonTypeTemplateParmDecl(hasName("N"))));
1188 EXPECT_TRUE(
1189 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
1190}
1191
Eric Fiselier3acf5fd2015-10-17 02:34:44 +00001192TEST(Matcher, templateTypeParmDecl) {
1193 EXPECT_TRUE(matches("template <typename T> void f();",
1194 templateTypeParmDecl(hasName("T"))));
1195 EXPECT_TRUE(
1196 notMatches("template <int N> void f();", templateTypeParmDecl()));
1197}
1198
Daniel Jasper5901e472012-10-01 13:40:41 +00001199TEST(Matcher, UserDefinedLiteral) {
1200 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1201 " return i + 1;"
1202 "}"
1203 "char c = 'a'_inc;",
1204 userDefinedLiteral()));
1205}
1206
Daniel Jasper87c3d362012-09-20 14:12:57 +00001207TEST(Matcher, FlowControl) {
1208 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1209 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1210 continueStmt()));
1211 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1212 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1213 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1214}
1215
Daniel Jasper1dad1832012-07-10 20:20:19 +00001216TEST(HasType, MatchesAsString) {
1217 EXPECT_TRUE(
1218 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00001219 cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
1220 EXPECT_TRUE(
1221 matches("class X { void x(int x) {} };",
1222 cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001223 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001224 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001225 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001226 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001227}
1228
Manuel Klimek04616e42012-07-06 05:48:52 +00001229TEST(Matcher, OverloadedOperatorCall) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001230 StatementMatcher OpCall = cxxOperatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001231 // Unary operator
1232 EXPECT_TRUE(matches("class Y { }; "
1233 "bool operator!(Y x) { return false; }; "
1234 "Y y; bool c = !y;", OpCall));
1235 // No match -- special operators like "new", "delete"
1236 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1237 // we need to figure out include paths in the test.
1238 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1239 // "class Y { }; "
1240 // "void *operator new(size_t size) { return 0; } "
1241 // "Y *y = new Y;", OpCall));
1242 EXPECT_TRUE(notMatches("class Y { }; "
1243 "void operator delete(void *p) { } "
1244 "void a() {Y *y = new Y; delete y;}", OpCall));
1245 // Binary operator
1246 EXPECT_TRUE(matches("class Y { }; "
1247 "bool operator&&(Y x, Y y) { return true; }; "
1248 "Y a; Y b; bool c = a && b;",
1249 OpCall));
1250 // No match -- normal operator, not an overloaded one.
1251 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1252 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1253}
1254
1255TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1256 StatementMatcher OpCallAndAnd =
Aaron Ballman512fb642015-09-17 13:30:52 +00001257 cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001258 EXPECT_TRUE(matches("class Y { }; "
1259 "bool operator&&(Y x, Y y) { return true; }; "
1260 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1261 StatementMatcher OpCallLessLess =
Aaron Ballman512fb642015-09-17 13:30:52 +00001262 cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001263 EXPECT_TRUE(notMatches("class Y { }; "
1264 "bool operator&&(Y x, Y y) { return true; }; "
1265 "Y a; Y b; bool c = a && b;",
1266 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001267 StatementMatcher OpStarCall =
Aaron Ballman512fb642015-09-17 13:30:52 +00001268 cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
Benjamin Kramer09514492014-07-14 14:05:02 +00001269 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1270 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001271 DeclarationMatcher ClassWithOpStar =
Aaron Ballman512fb642015-09-17 13:30:52 +00001272 cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001273 EXPECT_TRUE(matches("class Y { int operator*(); };",
1274 ClassWithOpStar));
1275 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1276 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001277 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1278 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1279 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001280}
1281
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001282TEST(Matcher, NestedOverloadedOperatorCalls) {
1283 EXPECT_TRUE(matchAndVerifyResultTrue(
Aaron Ballman512fb642015-09-17 13:30:52 +00001284 "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(hasOverloadedOperatorName("&&")).bind("x"),
1288 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1289 EXPECT_TRUE(matches("class Y { }; "
1290 "Y& operator&&(Y& x, Y& y) { return x; }; "
1291 "Y a; Y b; Y c; Y d = a && b && c;",
1292 cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
1293 EXPECT_TRUE(
1294 matches("class Y { }; "
1295 "Y& operator&&(Y& x, Y& y) { return x; }; "
1296 "Y a; Y b; Y c; Y d = a && b && c;",
1297 cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001298}
1299
Manuel Klimek04616e42012-07-06 05:48:52 +00001300TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001301 StatementMatcher MethodOnY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001302 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001303
1304 EXPECT_TRUE(
1305 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1306 MethodOnY));
1307 EXPECT_TRUE(
1308 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1309 MethodOnY));
1310 EXPECT_TRUE(
1311 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1312 MethodOnY));
1313 EXPECT_TRUE(
1314 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1315 MethodOnY));
1316 EXPECT_TRUE(
1317 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1318 MethodOnY));
1319
1320 EXPECT_TRUE(matches(
1321 "class Y {"
1322 " public: virtual void x();"
1323 "};"
1324 "class X : public Y {"
1325 " public: virtual void x();"
1326 "};"
1327 "void z() { X *x; x->Y::x(); }", MethodOnY));
1328}
1329
1330TEST(Matcher, VariableUsage) {
1331 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001332 declRefExpr(to(
1333 varDecl(hasInitializer(
Aaron Ballman512fb642015-09-17 13:30:52 +00001334 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001335
1336 EXPECT_TRUE(matches(
1337 "class Y {"
1338 " public:"
1339 " bool x() const;"
1340 "};"
1341 "void z(const Y &y) {"
1342 " bool b = y.x();"
1343 " if (b) {}"
1344 "}", Reference));
1345
1346 EXPECT_TRUE(notMatches(
1347 "class Y {"
1348 " public:"
1349 " bool x() const;"
1350 "};"
1351 "void z(const Y &y) {"
1352 " bool b = y.x();"
1353 "}", Reference));
1354}
1355
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001356TEST(Matcher, VarDecl_Storage) {
1357 auto M = varDecl(hasName("X"), hasLocalStorage());
1358 EXPECT_TRUE(matches("void f() { int X; }", M));
1359 EXPECT_TRUE(notMatches("int X;", M));
1360 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1361
1362 M = varDecl(hasName("X"), hasGlobalStorage());
1363 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1364 EXPECT_TRUE(matches("int X;", M));
1365 EXPECT_TRUE(matches("void f() { static int X; }", M));
1366}
1367
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001368TEST(Matcher, VarDecl_StorageDuration) {
1369 std::string T =
Aaron Ballmanf08e1842015-11-18 18:37:29 +00001370 "void f() { int x; static int y; } int a;";
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001371
1372 EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
1373 EXPECT_TRUE(
1374 notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
1375 EXPECT_TRUE(
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001376 notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
1377
1378 EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
1379 EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
1380 EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001381
Aaron Ballmanf08e1842015-11-18 18:37:29 +00001382 // FIXME: It is really hard to test with thread_local itself because not all
1383 // targets support TLS, which causes this to be an error depending on what
1384 // platform the test is being run on. We do not have access to the TargetInfo
1385 // object to be able to test whether the platform supports TLS or not.
Aaron Ballman8e7f00b2015-11-18 17:56:55 +00001386 EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
1387 EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
1388 EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
1389}
1390
Manuel Klimek61379422012-12-04 14:42:08 +00001391TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001392 EXPECT_TRUE(matches(
1393 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001394 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001395}
1396
Manuel Klimek04616e42012-07-06 05:48:52 +00001397TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001398 StatementMatcher CallOnVariableY =
Aaron Ballman512fb642015-09-17 13:30:52 +00001399 cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001400
1401 EXPECT_TRUE(matches(
1402 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1403 EXPECT_TRUE(matches(
1404 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1405 EXPECT_TRUE(matches(
1406 "class Y { public: void x(); };"
1407 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1408 EXPECT_TRUE(matches(
1409 "class Y { public: void x(); };"
1410 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1411 EXPECT_TRUE(notMatches(
1412 "class Y { public: void x(); };"
1413 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1414 CallOnVariableY));
1415}
1416
Daniel Jasper1dad1832012-07-10 20:20:19 +00001417TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1418 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1419 unaryExprOrTypeTraitExpr()));
1420 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1421 alignOfExpr(anything())));
1422 // FIXME: Uncomment once alignof is enabled.
1423 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1424 // unaryExprOrTypeTraitExpr()));
1425 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1426 // sizeOfExpr()));
1427}
1428
1429TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1430 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1431 hasArgumentOfType(asString("int")))));
1432 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1433 hasArgumentOfType(asString("float")))));
1434 EXPECT_TRUE(matches(
1435 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001436 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001437 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001438 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001439}
1440
Manuel Klimek04616e42012-07-06 05:48:52 +00001441TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001442 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001443}
1444
1445TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001446 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001447}
1448
1449TEST(MemberExpression, MatchesVariable) {
1450 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001451 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001452 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001453 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001454 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001455 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001456}
1457
1458TEST(MemberExpression, MatchesStaticVariable) {
1459 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001460 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001461 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001462 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001463 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001464 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001465}
1466
Daniel Jasper4e566c42012-07-12 08:50:38 +00001467TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001468 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1469 EXPECT_TRUE(matches(
1470 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1471 callExpr(hasArgument(0, declRefExpr(
1472 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001473}
1474
1475TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001476 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001477 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001478 callExpr(hasArgument(0, declRefExpr(
1479 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001480}
1481
Felix Bergercc9df3b2016-02-15 04:00:39 +00001482TEST(IsAnyPointer, MatchesPointers) {
1483 EXPECT_TRUE(matches("int* i = nullptr;", varDecl(hasType(isAnyPointer()))));
1484}
1485
Felix Berger40ef42a2016-03-06 15:27:59 +00001486TEST(IsAnyPointer, MatchesObjcPointer) {
1487 EXPECT_TRUE(matchesObjC("@interface Foo @end Foo *f;",
1488 varDecl(hasType(isAnyPointer()))));
1489}
1490
Felix Bergercc9df3b2016-02-15 04:00:39 +00001491TEST(IsAnyPointer, ReportsNoFalsePositives) {
1492 EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isAnyPointer()))));
1493}
1494
Gabor Horvath009c5d52015-12-15 08:35:45 +00001495TEST(IsAnyCharacter, MatchesCharacters) {
1496 EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
1497}
1498
1499TEST(IsAnyCharacter, ReportsNoFalsePositives) {
1500 EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
1501}
1502
Manuel Klimek04616e42012-07-06 05:48:52 +00001503TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1504 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001505 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001506 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001507 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001508 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001509 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001510}
1511
1512TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1513 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001514 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001515 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001516 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001517 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001518 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001519}
1520
1521TEST(IsArrow, MatchesMemberCallsViaArrow) {
1522 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001523 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001524 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001525 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001526 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001527 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001528}
1529
1530TEST(Callee, MatchesDeclarations) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001531 StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001532
1533 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1534 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001535
Aaron Ballman512fb642015-09-17 13:30:52 +00001536 CallMethodX = callExpr(callee(cxxConversionDecl()));
Samuel Benzaquen025f6b12015-04-20 20:58:50 +00001537 EXPECT_TRUE(
1538 matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
1539 EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
1540 CallMethodX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001541}
1542
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001543TEST(ConversionDeclaration, IsExplicit) {
1544 EXPECT_TRUE(matches("struct S { explicit operator int(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001545 cxxConversionDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001546 EXPECT_TRUE(notMatches("struct S { operator int(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001547 cxxConversionDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00001548}
1549
Manuel Klimek04616e42012-07-06 05:48:52 +00001550TEST(Callee, MatchesMemberExpressions) {
1551 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001552 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001553 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001554 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001555}
1556
1557TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001558 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001559
1560 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1561 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1562
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001563 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1564 llvm::Triple::Win32) {
1565 // FIXME: Make this work for MSVC.
1566 // Dependent contexts, but a non-dependent call.
1567 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1568 CallFunctionF));
1569 EXPECT_TRUE(
1570 matches("void f(); template <int N> struct S { void g() { f(); } };",
1571 CallFunctionF));
1572 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001573
1574 // Depedent calls don't match.
1575 EXPECT_TRUE(
1576 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1577 CallFunctionF));
1578 EXPECT_TRUE(
1579 notMatches("void f(int);"
1580 "template <typename T> struct S { void g(T t) { f(t); } };",
1581 CallFunctionF));
Aaron Ballman3fd6c112015-10-05 14:41:27 +00001582
1583 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
1584 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
1585 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
1586 functionDecl(isVariadic())));
1587 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
1588 EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
Aaron Ballman7e7b7b22016-02-01 14:11:47 +00001589 EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
1590 EXPECT_TRUE(matchesC("void f();", functionDecl(parameterCountIs(0))));
1591 EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001592}
1593
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001594TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1595 EXPECT_TRUE(
1596 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001597 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001598}
1599
1600TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1601 EXPECT_TRUE(
1602 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001603 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001604}
1605
1606TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1607 EXPECT_TRUE(
1608 notMatches("void g(); template <typename T> void f(T t) {}"
1609 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001610 functionTemplateDecl(hasName("f"),
1611 hasDescendant(declRefExpr(to(
1612 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001613}
1614
Manuel Klimek04616e42012-07-06 05:48:52 +00001615TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001616 StatementMatcher CallArgumentY = callExpr(
1617 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001618
1619 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1620 EXPECT_TRUE(
1621 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1622 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1623
Daniel Jasper848cbe12012-09-18 13:09:13 +00001624 StatementMatcher WrongIndex = callExpr(
1625 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001626 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1627}
1628
1629TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001630 StatementMatcher CallArgumentY = callExpr(
1631 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001632 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1633 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1634 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1635}
1636
Manuel Klimekce28f9e2016-01-18 11:20:09 +00001637TEST(ForEachArgumentWithParam, ReportsNoFalsePositives) {
1638 StatementMatcher ArgumentY =
1639 declRefExpr(to(varDecl(hasName("y")))).bind("arg");
1640 DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
1641 StatementMatcher CallExpr =
1642 callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1643
1644 // IntParam does not match.
Aaron Ballmand7b18b92016-01-18 20:28:57 +00001645 EXPECT_TRUE(notMatches("void f(int* i) { int* y; f(y); }", CallExpr));
Manuel Klimekce28f9e2016-01-18 11:20:09 +00001646 // ArgumentY does not match.
Aaron Ballmand7b18b92016-01-18 20:28:57 +00001647 EXPECT_TRUE(notMatches("void f(int i) { int x; f(x); }", CallExpr));
Manuel Klimekce28f9e2016-01-18 11:20:09 +00001648}
1649
1650TEST(ForEachArgumentWithParam, MatchesCXXMemberCallExpr) {
1651 StatementMatcher ArgumentY =
1652 declRefExpr(to(varDecl(hasName("y")))).bind("arg");
1653 DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
1654 StatementMatcher CallExpr =
1655 callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1656 EXPECT_TRUE(matchAndVerifyResultTrue(
1657 "struct S {"
1658 " const S& operator[](int i) { return *this; }"
1659 "};"
1660 "void f(S S1) {"
1661 " int y = 1;"
1662 " S1[y];"
1663 "}",
1664 CallExpr, new VerifyIdIsBoundTo<ParmVarDecl>("param", 1)));
Aaron Ballmand7b18b92016-01-18 20:28:57 +00001665
1666 StatementMatcher CallExpr2 =
1667 callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1668 EXPECT_TRUE(matchAndVerifyResultTrue(
1669 "struct S {"
1670 " static void g(int i);"
1671 "};"
1672 "void f() {"
1673 " int y = 1;"
1674 " S::g(y);"
1675 "}",
1676 CallExpr2, new VerifyIdIsBoundTo<ParmVarDecl>("param", 1)));
Manuel Klimekce28f9e2016-01-18 11:20:09 +00001677}
1678
1679TEST(ForEachArgumentWithParam, MatchesCallExpr) {
1680 StatementMatcher ArgumentY =
1681 declRefExpr(to(varDecl(hasName("y")))).bind("arg");
1682 DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
1683 StatementMatcher CallExpr =
1684 callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1685
1686 EXPECT_TRUE(
1687 matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr,
1688 new VerifyIdIsBoundTo<ParmVarDecl>("param")));
1689 EXPECT_TRUE(
1690 matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr,
1691 new VerifyIdIsBoundTo<DeclRefExpr>("arg")));
1692
1693 EXPECT_TRUE(matchAndVerifyResultTrue(
1694 "void f(int i, int j) { int y; f(y, y); }", CallExpr,
1695 new VerifyIdIsBoundTo<ParmVarDecl>("param", 2)));
1696 EXPECT_TRUE(matchAndVerifyResultTrue(
1697 "void f(int i, int j) { int y; f(y, y); }", CallExpr,
1698 new VerifyIdIsBoundTo<DeclRefExpr>("arg", 2)));
1699}
1700
1701TEST(ForEachArgumentWithParam, MatchesConstructExpr) {
1702 StatementMatcher ArgumentY =
1703 declRefExpr(to(varDecl(hasName("y")))).bind("arg");
1704 DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
1705 StatementMatcher ConstructExpr =
1706 cxxConstructExpr(forEachArgumentWithParam(ArgumentY, IntParam));
1707
1708 EXPECT_TRUE(matchAndVerifyResultTrue(
1709 "struct C {"
1710 " C(int i) {}"
1711 "};"
1712 "int y = 0;"
1713 "C Obj(y);",
1714 ConstructExpr, new VerifyIdIsBoundTo<ParmVarDecl>("param")));
1715}
1716
1717TEST(ForEachArgumentWithParam, HandlesBoundNodesForNonMatches) {
1718 EXPECT_TRUE(matchAndVerifyResultTrue(
1719 "void g(int i, int j) {"
1720 " int a;"
1721 " int b;"
1722 " int c;"
1723 " g(a, 0);"
1724 " g(a, b);"
1725 " g(0, b);"
1726 "}",
1727 functionDecl(
1728 forEachDescendant(varDecl().bind("v")),
1729 forEachDescendant(callExpr(forEachArgumentWithParam(
1730 declRefExpr(to(decl(equalsBoundNode("v")))), parmVarDecl())))),
1731 new VerifyIdIsBoundTo<VarDecl>("v", 4)));
1732}
1733
Manuel Klimek04616e42012-07-06 05:48:52 +00001734TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001735 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001736
1737 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1738 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1739 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1740}
1741
Daniel Jasper9f501292012-12-04 11:54:27 +00001742TEST(Matcher, ParameterCount) {
1743 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1744 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1745 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1746 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1747 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
Aaron Ballman7e7b7b22016-02-01 14:11:47 +00001748 EXPECT_TRUE(matches("void f(int i, ...) {};", Function1Arg));
Daniel Jasper9f501292012-12-04 11:54:27 +00001749}
1750
Manuel Klimek04616e42012-07-06 05:48:52 +00001751TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001752 DeclarationMatcher ReferenceClassX = varDecl(
1753 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001754 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1755 ReferenceClassX));
1756 EXPECT_TRUE(
1757 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001758 // The match here is on the implicit copy constructor code for
1759 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001760 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001761 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1762 EXPECT_TRUE(
1763 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001764 EXPECT_TRUE(
1765 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1766}
1767
Edwin Vane0a4836e2013-03-06 17:02:57 +00001768TEST(QualType, hasCanonicalType) {
1769 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1770 "int a;"
1771 "int_ref b = a;",
1772 varDecl(hasType(qualType(referenceType())))));
1773 EXPECT_TRUE(
1774 matches("typedef int &int_ref;"
1775 "int a;"
1776 "int_ref b = a;",
1777 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1778}
1779
Edwin Vane119d3df2013-04-02 18:15:55 +00001780TEST(QualType, hasLocalQualifiers) {
1781 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1782 varDecl(hasType(hasLocalQualifiers()))));
1783 EXPECT_TRUE(matches("int *const j = nullptr;",
1784 varDecl(hasType(hasLocalQualifiers()))));
1785 EXPECT_TRUE(matches("int *volatile k;",
1786 varDecl(hasType(hasLocalQualifiers()))));
1787 EXPECT_TRUE(notMatches("int m;",
1788 varDecl(hasType(hasLocalQualifiers()))));
1789}
1790
Manuel Klimek04616e42012-07-06 05:48:52 +00001791TEST(HasParameter, CallsInnerMatcher) {
1792 EXPECT_TRUE(matches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001793 cxxMethodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001794 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001795 cxxMethodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001796}
1797
1798TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1799 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001800 cxxMethodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001801}
1802
1803TEST(HasType, MatchesParameterVariableTypesStrictly) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001804 EXPECT_TRUE(matches(
1805 "class X { void x(X x) {} };",
1806 cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
1807 EXPECT_TRUE(notMatches(
1808 "class X { void x(const X &x) {} };",
1809 cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001810 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001811 cxxMethodDecl(hasParameter(
1812 0, hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001813 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001814 cxxMethodDecl(hasParameter(
1815 0, hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001816}
1817
1818TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001819 EXPECT_TRUE(matches(
1820 "class Y {}; class X { void x(X x, Y y) {} };",
1821 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
1822 EXPECT_TRUE(matches(
1823 "class Y {}; class X { void x(Y y, X x) {} };",
1824 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001825}
1826
Daniel Jasper1dad1832012-07-10 20:20:19 +00001827TEST(Returns, MatchesReturnTypes) {
1828 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001829 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001830 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001831 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001832 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001833 functionDecl(returns(hasDeclaration(
1834 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001835}
1836
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001837TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001838 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1839 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1840 functionDecl(isExternC())));
1841 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001842}
1843
Aaron Ballmaneb85b042016-01-18 20:37:44 +00001844TEST(IsDefaulted, MatchesDefaultedFunctionDeclarations) {
Aaron Ballman9e373df2016-01-18 20:47:02 +00001845 EXPECT_TRUE(notMatches("class A { ~A(); };",
1846 functionDecl(hasName("~A"), isDefaulted())));
Aaron Ballmaneb85b042016-01-18 20:37:44 +00001847 EXPECT_TRUE(matches("class B { ~B() = default; };",
Aaron Ballman9e373df2016-01-18 20:47:02 +00001848 functionDecl(hasName("~B"), isDefaulted())));
Aaron Ballmaneb85b042016-01-18 20:37:44 +00001849}
1850
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001851TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1852 EXPECT_TRUE(
1853 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1854 EXPECT_TRUE(matches("void Func() = delete;",
1855 functionDecl(hasName("Func"), isDeleted())));
1856}
1857
Aaron Ballmana60bcda2015-12-02 15:23:59 +00001858TEST(IsNoThrow, MatchesNoThrowFunctionDeclarations) {
1859 EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
1860 EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
1861 EXPECT_TRUE(
1862 notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
1863 EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
1864 EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
1865}
1866
Szabolcs Siposb37b0ed2015-05-22 11:35:50 +00001867TEST(isConstexpr, MatchesConstexprDeclarations) {
1868 EXPECT_TRUE(matches("constexpr int foo = 42;",
1869 varDecl(hasName("foo"), isConstexpr())));
1870 EXPECT_TRUE(matches("constexpr int bar();",
1871 functionDecl(hasName("bar"), isConstexpr())));
1872}
1873
Manuel Klimek04616e42012-07-06 05:48:52 +00001874TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
Aaron Ballman512fb642015-09-17 13:30:52 +00001875 EXPECT_TRUE(notMatches(
1876 "class Y {}; class X { void x(int) {} };",
1877 cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001878}
1879
1880TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1881 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001882 cxxMethodDecl(hasAnyParameter(
1883 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001884}
1885
Alp Toker8db6e7a2014-01-05 06:38:57 +00001886TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001887 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001888 cxxMethodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001889 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00001890 cxxMethodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001891}
1892
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001893TEST(Matcher, MatchesClassTemplateSpecialization) {
1894 EXPECT_TRUE(matches("template<typename T> struct A {};"
1895 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001896 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001897 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001898 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001899 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001900 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001901}
1902
Manuel Klimekc16c6522013-06-20 13:08:29 +00001903TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1904 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1905 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1906}
1907
1908TEST(ParmVarDecl, MatchesParmVars) {
1909 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1910 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1911}
1912
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001913TEST(Matcher, MatchesTypeTemplateArgument) {
1914 EXPECT_TRUE(matches(
1915 "template<typename T> struct B {};"
1916 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001917 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001918 asString("int"))))));
1919}
1920
1921TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1922 EXPECT_TRUE(matches(
1923 "struct B { int next; };"
1924 "template<int(B::*next_ptr)> struct A {};"
1925 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001926 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1927 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001928
1929 EXPECT_TRUE(notMatches(
1930 "template <typename T> struct A {};"
1931 "A<int> a;",
1932 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1933 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001934
1935 EXPECT_TRUE(matches(
1936 "struct B { int next; };"
1937 "template<int(B::*next_ptr)> struct A {};"
1938 "A<&B::next> a;",
1939 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1940 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1941
1942 EXPECT_TRUE(notMatches(
1943 "template <typename T> struct A {};"
1944 "A<int> a;",
1945 templateSpecializationType(hasAnyTemplateArgument(
1946 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001947}
1948
1949TEST(Matcher, MatchesSpecificArgument) {
1950 EXPECT_TRUE(matches(
1951 "template<typename T, typename U> class A {};"
1952 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001953 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001954 1, refersToType(asString("int"))))));
1955 EXPECT_TRUE(notMatches(
1956 "template<typename T, typename U> class A {};"
1957 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001958 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001959 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001960
1961 EXPECT_TRUE(matches(
1962 "template<typename T, typename U> class A {};"
1963 "A<bool, int> a;",
1964 templateSpecializationType(hasTemplateArgument(
1965 1, refersToType(asString("int"))))));
1966 EXPECT_TRUE(notMatches(
1967 "template<typename T, typename U> class A {};"
1968 "A<int, bool> a;",
1969 templateSpecializationType(hasTemplateArgument(
1970 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001971}
1972
Manuel Klimek7735e402014-10-09 13:06:22 +00001973TEST(TemplateArgument, Matches) {
1974 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1975 classTemplateSpecializationDecl(
1976 hasAnyTemplateArgument(templateArgument()))));
1977 EXPECT_TRUE(matches(
1978 "template<typename T> struct C {}; C<int> c;",
1979 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1980}
1981
1982TEST(TemplateArgumentCountIs, Matches) {
1983 EXPECT_TRUE(
1984 matches("template<typename T> struct C {}; C<int> c;",
1985 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1986 EXPECT_TRUE(
1987 notMatches("template<typename T> struct C {}; C<int> c;",
1988 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1989
1990 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1991 templateSpecializationType(templateArgumentCountIs(1))));
1992 EXPECT_TRUE(
1993 notMatches("template<typename T> struct C {}; C<int> c;",
1994 templateSpecializationType(templateArgumentCountIs(2))));
1995}
1996
1997TEST(IsIntegral, Matches) {
1998 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1999 classTemplateSpecializationDecl(
2000 hasAnyTemplateArgument(isIntegral()))));
2001 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
2002 classTemplateSpecializationDecl(hasAnyTemplateArgument(
2003 templateArgument(isIntegral())))));
2004}
2005
2006TEST(RefersToIntegralType, Matches) {
2007 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
2008 classTemplateSpecializationDecl(
2009 hasAnyTemplateArgument(refersToIntegralType(
2010 asString("int"))))));
2011 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
2012 classTemplateSpecializationDecl(hasAnyTemplateArgument(
2013 refersToIntegralType(asString("int"))))));
2014}
2015
2016TEST(EqualsIntegralValue, Matches) {
2017 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
2018 classTemplateSpecializationDecl(
2019 hasAnyTemplateArgument(equalsIntegralValue("42")))));
2020 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
2021 classTemplateSpecializationDecl(
2022 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
2023 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
2024 classTemplateSpecializationDecl(
2025 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
2026 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
2027 classTemplateSpecializationDecl(hasAnyTemplateArgument(
2028 equalsIntegralValue("0042")))));
2029}
2030
Daniel Jasper639522c2013-02-25 12:02:08 +00002031TEST(Matcher, MatchesAccessSpecDecls) {
2032 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
2033 EXPECT_TRUE(
2034 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
2035 EXPECT_TRUE(
2036 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
2037 EXPECT_TRUE(
2038 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
2039
2040 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
2041}
2042
Aaron Ballman41143bb2015-07-24 12:35:41 +00002043TEST(Matcher, MatchesFinal) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002044 EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
Aaron Ballman41143bb2015-07-24 12:35:41 +00002045 EXPECT_TRUE(matches("class X { virtual void f() final; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002046 cxxMethodDecl(isFinal())));
2047 EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
2048 EXPECT_TRUE(
2049 notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
Aaron Ballman41143bb2015-07-24 12:35:41 +00002050}
2051
Edwin Vane37ee1d72013-04-09 20:46:36 +00002052TEST(Matcher, MatchesVirtualMethod) {
2053 EXPECT_TRUE(matches("class X { virtual int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002054 cxxMethodDecl(isVirtual(), hasName("::X::f"))));
2055 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002056}
2057
Nico Webera415a1d2016-01-21 17:56:24 +00002058TEST(Matcher, MatchesVirtualAsWrittenMethod) {
2059 EXPECT_TRUE(matches("class A { virtual int f(); };"
2060 "class B : public A { int f(); };",
2061 cxxMethodDecl(isVirtualAsWritten(), hasName("::A::f"))));
2062 EXPECT_TRUE(
2063 notMatches("class A { virtual int f(); };"
2064 "class B : public A { int f(); };",
2065 cxxMethodDecl(isVirtualAsWritten(), hasName("::B::f"))));
2066}
2067
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00002068TEST(Matcher, MatchesPureMethod) {
2069 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002070 cxxMethodDecl(isPure(), hasName("::X::f"))));
2071 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00002072}
2073
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00002074TEST(Matcher, MatchesCopyAssignmentOperator) {
2075 EXPECT_TRUE(matches("class X { X &operator=(X); };",
2076 cxxMethodDecl(isCopyAssignmentOperator())));
2077 EXPECT_TRUE(matches("class X { X &operator=(X &); };",
2078 cxxMethodDecl(isCopyAssignmentOperator())));
2079 EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
2080 cxxMethodDecl(isCopyAssignmentOperator())));
2081 EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
2082 cxxMethodDecl(isCopyAssignmentOperator())));
2083 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
2084 cxxMethodDecl(isCopyAssignmentOperator())));
2085 EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
2086 cxxMethodDecl(isCopyAssignmentOperator())));
2087}
2088
Aaron Ballman31bde872016-01-22 22:37:09 +00002089TEST(Matcher, MatchesMoveAssignmentOperator) {
2090 EXPECT_TRUE(notMatches("class X { X &operator=(X); };",
2091 cxxMethodDecl(isMoveAssignmentOperator())));
2092 EXPECT_TRUE(matches("class X { X &operator=(X &&); };",
2093 cxxMethodDecl(isMoveAssignmentOperator())));
2094 EXPECT_TRUE(matches("class X { X &operator=(const X &&); };",
2095 cxxMethodDecl(isMoveAssignmentOperator())));
2096 EXPECT_TRUE(matches("class X { X &operator=(volatile X &&); };",
2097 cxxMethodDecl(isMoveAssignmentOperator())));
2098 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &&); };",
2099 cxxMethodDecl(isMoveAssignmentOperator())));
2100 EXPECT_TRUE(notMatches("class X { X &operator=(X &); };",
2101 cxxMethodDecl(isMoveAssignmentOperator())));
2102}
2103
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00002104TEST(Matcher, MatchesConstMethod) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002105 EXPECT_TRUE(
2106 matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
2107 EXPECT_TRUE(
2108 notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00002109}
2110
Edwin Vane37ee1d72013-04-09 20:46:36 +00002111TEST(Matcher, MatchesOverridingMethod) {
2112 EXPECT_TRUE(matches("class X { virtual int f(); }; "
2113 "class Y : public X { int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002114 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002115 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
Aaron Ballman512fb642015-09-17 13:30:52 +00002116 "class Y : public X { int f(); };",
2117 cxxMethodDecl(isOverride(), hasName("::X::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002118 EXPECT_TRUE(notMatches("class X { int f(); }; "
2119 "class Y : public X { int f(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002120 cxxMethodDecl(isOverride())));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002121 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
Aaron Ballman512fb642015-09-17 13:30:52 +00002122 cxxMethodDecl(isOverride())));
Samuel Benzaquenbb5093f2015-03-06 16:24:47 +00002123 EXPECT_TRUE(
2124 matches("template <typename Base> struct Y : Base { void f() override;};",
Aaron Ballman512fb642015-09-17 13:30:52 +00002125 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
Edwin Vane37ee1d72013-04-09 20:46:36 +00002126}
2127
Manuel Klimek04616e42012-07-06 05:48:52 +00002128TEST(Matcher, ConstructorCall) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002129 StatementMatcher Constructor = cxxConstructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002130
2131 EXPECT_TRUE(
2132 matches("class X { public: X(); }; void x() { X x; }", Constructor));
2133 EXPECT_TRUE(
2134 matches("class X { public: X(); }; void x() { X x = X(); }",
2135 Constructor));
2136 EXPECT_TRUE(
2137 matches("class X { public: X(int); }; void x() { X x = 0; }",
2138 Constructor));
2139 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
2140}
2141
2142TEST(Matcher, ConstructorArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002143 StatementMatcher Constructor = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002144 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002145
2146 EXPECT_TRUE(
2147 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
2148 Constructor));
2149 EXPECT_TRUE(
2150 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
2151 Constructor));
2152 EXPECT_TRUE(
2153 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
2154 Constructor));
2155 EXPECT_TRUE(
2156 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
2157 Constructor));
2158
Aaron Ballman512fb642015-09-17 13:30:52 +00002159 StatementMatcher WrongIndex = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002160 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002161 EXPECT_TRUE(
2162 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
2163 WrongIndex));
2164}
2165
2166TEST(Matcher, ConstructorArgumentCount) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002167 StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002168
2169 EXPECT_TRUE(
2170 matches("class X { public: X(int); }; void x() { X x(0); }",
2171 Constructor1Arg));
2172 EXPECT_TRUE(
2173 matches("class X { public: X(int); }; void x() { X x = X(0); }",
2174 Constructor1Arg));
2175 EXPECT_TRUE(
2176 matches("class X { public: X(int); }; void x() { X x = 0; }",
2177 Constructor1Arg));
2178 EXPECT_TRUE(
2179 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
2180 Constructor1Arg));
2181}
2182
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00002183TEST(Matcher, ConstructorListInitialization) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002184 StatementMatcher ConstructorListInit =
2185 cxxConstructExpr(isListInitialization());
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00002186
2187 EXPECT_TRUE(
2188 matches("class X { public: X(int); }; void x() { X x{0}; }",
2189 ConstructorListInit));
2190 EXPECT_FALSE(
2191 matches("class X { public: X(int); }; void x() { X x(0); }",
2192 ConstructorListInit));
2193}
2194
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002195TEST(Matcher,ThisExpr) {
2196 EXPECT_TRUE(
Aaron Ballman512fb642015-09-17 13:30:52 +00002197 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002198 EXPECT_TRUE(
Aaron Ballman512fb642015-09-17 13:30:52 +00002199 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
Manuel Klimek7fca93b2012-10-23 10:40:50 +00002200}
2201
Manuel Klimek04616e42012-07-06 05:48:52 +00002202TEST(Matcher, BindTemporaryExpression) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002203 StatementMatcher TempExpression = cxxBindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002204
2205 std::string ClassString = "class string { public: string(); ~string(); }; ";
2206
2207 EXPECT_TRUE(
2208 matches(ClassString +
2209 "string GetStringByValue();"
2210 "void FunctionTakesString(string s);"
2211 "void run() { FunctionTakesString(GetStringByValue()); }",
2212 TempExpression));
2213
2214 EXPECT_TRUE(
2215 notMatches(ClassString +
2216 "string* GetStringPointer(); "
2217 "void FunctionTakesStringPtr(string* s);"
2218 "void run() {"
2219 " string* s = GetStringPointer();"
2220 " FunctionTakesStringPtr(GetStringPointer());"
2221 " FunctionTakesStringPtr(s);"
2222 "}",
2223 TempExpression));
2224
2225 EXPECT_TRUE(
2226 notMatches("class no_dtor {};"
2227 "no_dtor GetObjByValue();"
2228 "void ConsumeObj(no_dtor param);"
2229 "void run() { ConsumeObj(GetObjByValue()); }",
2230 TempExpression));
2231}
2232
Sam Panzer68a35af2012-08-24 22:04:44 +00002233TEST(MaterializeTemporaryExpr, MatchesTemporary) {
2234 std::string ClassString =
2235 "class string { public: string(); int length(); }; ";
2236
2237 EXPECT_TRUE(
2238 matches(ClassString +
2239 "string GetStringByValue();"
2240 "void FunctionTakesString(string s);"
2241 "void run() { FunctionTakesString(GetStringByValue()); }",
2242 materializeTemporaryExpr()));
2243
2244 EXPECT_TRUE(
2245 notMatches(ClassString +
2246 "string* GetStringPointer(); "
2247 "void FunctionTakesStringPtr(string* s);"
2248 "void run() {"
2249 " string* s = GetStringPointer();"
2250 " FunctionTakesStringPtr(GetStringPointer());"
2251 " FunctionTakesStringPtr(s);"
2252 "}",
2253 materializeTemporaryExpr()));
2254
2255 EXPECT_TRUE(
2256 notMatches(ClassString +
2257 "string GetStringByValue();"
2258 "void run() { int k = GetStringByValue().length(); }",
2259 materializeTemporaryExpr()));
2260
2261 EXPECT_TRUE(
2262 notMatches(ClassString +
2263 "string GetStringByValue();"
2264 "void run() { GetStringByValue(); }",
2265 materializeTemporaryExpr()));
2266}
2267
Manuel Klimek04616e42012-07-06 05:48:52 +00002268TEST(ConstructorDeclaration, SimpleCase) {
2269 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002270 cxxConstructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002271 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002272 cxxConstructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002273}
2274
2275TEST(ConstructorDeclaration, IsImplicit) {
2276 // This one doesn't match because the constructor is not added by the
2277 // compiler (it is not needed).
2278 EXPECT_TRUE(notMatches("class Foo { };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002279 cxxConstructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002280 // The compiler added the implicit default constructor.
2281 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Aaron Ballman512fb642015-09-17 13:30:52 +00002282 cxxConstructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00002283 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002284 cxxConstructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00002285 // The compiler added an implicit assignment operator.
2286 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002287 cxxMethodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002288}
2289
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002290TEST(ConstructorDeclaration, IsExplicit) {
2291 EXPECT_TRUE(matches("struct S { explicit S(int); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002292 cxxConstructorDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002293 EXPECT_TRUE(notMatches("struct S { S(int); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002294 cxxConstructorDecl(isExplicit())));
Aaron Ballman6f6d0b62015-08-11 21:09:52 +00002295}
2296
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002297TEST(ConstructorDeclaration, Kinds) {
2298 EXPECT_TRUE(matches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002299 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002300 EXPECT_TRUE(notMatches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002301 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002302 EXPECT_TRUE(notMatches("struct S { S(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002303 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002304
2305 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002306 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002307 EXPECT_TRUE(matches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002308 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002309 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002310 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002311
2312 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002313 cxxConstructorDecl(isDefaultConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002314 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002315 cxxConstructorDecl(isCopyConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002316 EXPECT_TRUE(matches("struct S { S(S&&); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002317 cxxConstructorDecl(isMoveConstructor())));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002318}
2319
Daniel Jasper1dad1832012-07-10 20:20:19 +00002320TEST(DestructorDeclaration, MatchesVirtualDestructor) {
2321 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00002322 cxxDestructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002323}
2324
2325TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002326 EXPECT_TRUE(notMatches("class Foo {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00002327 cxxDestructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002328}
2329
Manuel Klimek04616e42012-07-06 05:48:52 +00002330TEST(HasAnyConstructorInitializer, SimpleCase) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002331 EXPECT_TRUE(
2332 notMatches("class Foo { Foo() { } };",
2333 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
2334 EXPECT_TRUE(
2335 matches("class Foo {"
2336 " Foo() : foo_() { }"
2337 " int foo_;"
2338 "};",
2339 cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002340}
2341
2342TEST(HasAnyConstructorInitializer, ForField) {
2343 static const char Code[] =
2344 "class Baz { };"
2345 "class Foo {"
2346 " Foo() : foo_() { }"
2347 " Baz foo_;"
2348 " Baz bar_;"
2349 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002350 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002351 forField(hasType(recordDecl(hasName("Baz"))))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002352 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002353 forField(hasName("foo_"))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002354 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002355 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002356}
2357
2358TEST(HasAnyConstructorInitializer, WithInitializer) {
2359 static const char Code[] =
2360 "class Foo {"
2361 " Foo() : foo_(0) { }"
2362 " int foo_;"
2363 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002364 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002365 withInitializer(integerLiteral(equals(0)))))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002366 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002367 withInitializer(integerLiteral(equals(1)))))));
2368}
2369
2370TEST(HasAnyConstructorInitializer, IsWritten) {
2371 static const char Code[] =
2372 "struct Bar { Bar(){} };"
2373 "class Foo {"
2374 " Foo() : foo_() { }"
2375 " Bar foo_;"
2376 " Bar bar_;"
2377 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002378 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002379 allOf(forField(hasName("foo_")), isWritten())))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002380 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002381 allOf(forField(hasName("bar_")), isWritten())))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002382 EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002383 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2384}
2385
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002386TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
2387 static const char Code[] =
2388 "struct B {};"
2389 "struct D : B {"
2390 " int I;"
2391 " D(int i) : I(i) {}"
2392 "};"
2393 "struct E : B {"
2394 " E() : B() {}"
2395 "};";
Aaron Ballman512fb642015-09-17 13:30:52 +00002396 EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002397 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2398 hasName("E")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002399 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002400 hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
2401 hasName("D")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002402 EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
Aaron Ballmaned455d42015-08-11 20:42:00 +00002403 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2404 hasName("D")))));
Aaron Ballman512fb642015-09-17 13:30:52 +00002405 EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
Aaron Ballmaned455d42015-08-11 20:42:00 +00002406 hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
2407 hasName("E")))));
Aaron Ballman1ca258e2015-08-05 12:11:30 +00002408}
2409
Manuel Klimek04616e42012-07-06 05:48:52 +00002410TEST(Matcher, NewExpression) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002411 StatementMatcher New = cxxNewExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002412
2413 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2414 EXPECT_TRUE(
2415 matches("class X { public: X(); }; void x() { new X(); }", New));
2416 EXPECT_TRUE(
2417 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2418 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2419}
2420
2421TEST(Matcher, NewExpressionArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002422 StatementMatcher New = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002423 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002424
2425 EXPECT_TRUE(
2426 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2427 New));
2428 EXPECT_TRUE(
2429 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2430 New));
2431 EXPECT_TRUE(
2432 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2433 New));
2434
Aaron Ballman512fb642015-09-17 13:30:52 +00002435 StatementMatcher WrongIndex = cxxConstructExpr(
Daniel Jasper848cbe12012-09-18 13:09:13 +00002436 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002437 EXPECT_TRUE(
2438 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2439 WrongIndex));
2440}
2441
2442TEST(Matcher, NewExpressionArgumentCount) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002443 StatementMatcher New = cxxConstructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002444
2445 EXPECT_TRUE(
2446 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2447 EXPECT_TRUE(
2448 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2449 New));
2450}
2451
Daniel Jasper1dad1832012-07-10 20:20:19 +00002452TEST(Matcher, DeleteExpression) {
2453 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002454 cxxDeleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002455}
2456
Manuel Klimek04616e42012-07-06 05:48:52 +00002457TEST(Matcher, DefaultArgument) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002458 StatementMatcher Arg = cxxDefaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002459
2460 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2461 EXPECT_TRUE(
2462 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2463 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2464}
2465
2466TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002467 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002468 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2469 // wide string
2470 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2471 // with escaped characters
2472 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2473 // no matching -- though the data type is the same, there is no string literal
2474 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2475}
2476
2477TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002478 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002479 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2480 // wide character
2481 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2482 // wide character, Hex encoded, NOT MATCHED!
2483 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2484 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2485}
2486
2487TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002488 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002489 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2490 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2491 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2492 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2493
2494 // Non-matching cases (character literals, float and double)
2495 EXPECT_TRUE(notMatches("int i = L'a';",
2496 HasIntLiteral)); // this is actually a character
2497 // literal cast to int
2498 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2499 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2500 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2501}
2502
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002503TEST(Matcher, FloatLiterals) {
2504 StatementMatcher HasFloatLiteral = floatLiteral();
2505 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2506 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2507 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2508 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2509 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002510 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2511 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2512 EXPECT_TRUE(
2513 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002514
2515 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002516 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2517 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2518 EXPECT_TRUE(
2519 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002520}
2521
Daniel Jasper5901e472012-10-01 13:40:41 +00002522TEST(Matcher, NullPtrLiteral) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002523 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
Daniel Jasper5901e472012-10-01 13:40:41 +00002524}
2525
Szabolcs Sipos1d068bb2015-05-07 14:24:22 +00002526TEST(Matcher, GNUNullExpr) {
2527 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
2528}
2529
Daniel Jasper87c3d362012-09-20 14:12:57 +00002530TEST(Matcher, AsmStatement) {
2531 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2532}
2533
Manuel Klimek04616e42012-07-06 05:48:52 +00002534TEST(Matcher, Conditions) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002535 StatementMatcher Condition =
2536 ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002537
2538 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2539 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2540 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2541 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2542 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2543}
2544
Manuel Klimek909b5c942014-05-27 10:04:12 +00002545TEST(IfStmt, ChildTraversalMatchers) {
2546 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002547 ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002548 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002549 ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002550 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002551 ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002552 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002553 ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
Manuel Klimek909b5c942014-05-27 10:04:12 +00002554}
2555
Manuel Klimek04616e42012-07-06 05:48:52 +00002556TEST(MatchBinaryOperator, HasOperatorName) {
2557 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2558
2559 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2560 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2561}
2562
2563TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2564 StatementMatcher OperatorTrueFalse =
Aaron Ballman512fb642015-09-17 13:30:52 +00002565 binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
2566 hasRHS(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002567
2568 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2569 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2570 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
Alexander Kornienkoe39993e2015-11-02 22:23:21 +00002571
2572 StatementMatcher OperatorIntPointer = arraySubscriptExpr(
2573 hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
2574 EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
2575 EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
Manuel Klimek04616e42012-07-06 05:48:52 +00002576}
2577
2578TEST(MatchBinaryOperator, HasEitherOperand) {
2579 StatementMatcher HasOperand =
Aaron Ballman512fb642015-09-17 13:30:52 +00002580 binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002581
2582 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2583 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2584 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2585}
2586
2587TEST(Matcher, BinaryOperatorTypes) {
2588 // Integration test that verifies the AST provides all binary operators in
2589 // a way we expect.
2590 // FIXME: Operator ','
2591 EXPECT_TRUE(
2592 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2593 EXPECT_TRUE(
2594 matches("bool b; bool c = (b = true);",
2595 binaryOperator(hasOperatorName("="))));
2596 EXPECT_TRUE(
2597 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2598 EXPECT_TRUE(
2599 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2600 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2601 EXPECT_TRUE(
2602 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2603 EXPECT_TRUE(
2604 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2605 EXPECT_TRUE(
2606 matches("int i = 1; int j = (i <<= 2);",
2607 binaryOperator(hasOperatorName("<<="))));
2608 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2609 EXPECT_TRUE(
2610 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2611 EXPECT_TRUE(
2612 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2613 EXPECT_TRUE(
2614 matches("int i = 1; int j = (i >>= 2);",
2615 binaryOperator(hasOperatorName(">>="))));
2616 EXPECT_TRUE(
2617 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2618 EXPECT_TRUE(
2619 matches("int i = 42; int j = (i ^= 42);",
2620 binaryOperator(hasOperatorName("^="))));
2621 EXPECT_TRUE(
2622 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2623 EXPECT_TRUE(
2624 matches("int i = 42; int j = (i %= 42);",
2625 binaryOperator(hasOperatorName("%="))));
2626 EXPECT_TRUE(
2627 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2628 EXPECT_TRUE(
2629 matches("bool b = true && false;",
2630 binaryOperator(hasOperatorName("&&"))));
2631 EXPECT_TRUE(
2632 matches("bool b = true; bool c = (b &= false);",
2633 binaryOperator(hasOperatorName("&="))));
2634 EXPECT_TRUE(
2635 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2636 EXPECT_TRUE(
2637 matches("bool b = true || false;",
2638 binaryOperator(hasOperatorName("||"))));
2639 EXPECT_TRUE(
2640 matches("bool b = true; bool c = (b |= false);",
2641 binaryOperator(hasOperatorName("|="))));
2642 EXPECT_TRUE(
2643 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2644 EXPECT_TRUE(
2645 matches("int i = 42; int j = (i *= 23);",
2646 binaryOperator(hasOperatorName("*="))));
2647 EXPECT_TRUE(
2648 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2649 EXPECT_TRUE(
2650 matches("int i = 42; int j = (i /= 23);",
2651 binaryOperator(hasOperatorName("/="))));
2652 EXPECT_TRUE(
2653 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2654 EXPECT_TRUE(
2655 matches("int i = 42; int j = (i += 23);",
2656 binaryOperator(hasOperatorName("+="))));
2657 EXPECT_TRUE(
2658 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2659 EXPECT_TRUE(
2660 matches("int i = 42; int j = (i -= 23);",
2661 binaryOperator(hasOperatorName("-="))));
2662 EXPECT_TRUE(
2663 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2664 binaryOperator(hasOperatorName("->*"))));
2665 EXPECT_TRUE(
2666 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2667 binaryOperator(hasOperatorName(".*"))));
2668
2669 // Member expressions as operators are not supported in matches.
2670 EXPECT_TRUE(
2671 notMatches("struct A { void x(A *a) { a->x(this); } };",
2672 binaryOperator(hasOperatorName("->"))));
2673
2674 // Initializer assignments are not represented as operator equals.
2675 EXPECT_TRUE(
2676 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2677
2678 // Array indexing is not represented as operator.
2679 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2680
2681 // Overloaded operators do not match at all.
2682 EXPECT_TRUE(notMatches(
2683 "struct A { bool operator&&(const A &a) const { return false; } };"
2684 "void x() { A a, b; a && b; }",
2685 binaryOperator()));
2686}
2687
2688TEST(MatchUnaryOperator, HasOperatorName) {
2689 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2690
2691 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2692 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2693}
2694
2695TEST(MatchUnaryOperator, HasUnaryOperand) {
2696 StatementMatcher OperatorOnFalse =
Aaron Ballman512fb642015-09-17 13:30:52 +00002697 unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002698
2699 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2700 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2701}
2702
2703TEST(Matcher, UnaryOperatorTypes) {
2704 // Integration test that verifies the AST provides all unary operators in
2705 // a way we expect.
2706 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2707 EXPECT_TRUE(
2708 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2709 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2710 EXPECT_TRUE(
2711 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2712 EXPECT_TRUE(
2713 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2714 EXPECT_TRUE(
2715 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2716 EXPECT_TRUE(
2717 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2718 EXPECT_TRUE(
2719 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2720 EXPECT_TRUE(
2721 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2722 EXPECT_TRUE(
2723 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2724
2725 // We don't match conversion operators.
2726 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2727
2728 // Function calls are not represented as operator.
2729 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2730
2731 // Overloaded operators do not match at all.
2732 // FIXME: We probably want to add that.
2733 EXPECT_TRUE(notMatches(
2734 "struct A { bool operator!() const { return false; } };"
2735 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2736}
2737
2738TEST(Matcher, ConditionalOperator) {
2739 StatementMatcher Conditional = conditionalOperator(
Aaron Ballman512fb642015-09-17 13:30:52 +00002740 hasCondition(cxxBoolLiteral(equals(true))),
2741 hasTrueExpression(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002742
2743 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2744 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2745 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2746
2747 StatementMatcher ConditionalFalse = conditionalOperator(
Aaron Ballman512fb642015-09-17 13:30:52 +00002748 hasFalseExpression(cxxBoolLiteral(equals(false))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002749
2750 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2751 EXPECT_TRUE(
2752 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2753}
2754
Daniel Jasper1dad1832012-07-10 20:20:19 +00002755TEST(ArraySubscriptMatchers, ArraySubscripts) {
2756 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2757 arraySubscriptExpr()));
2758 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2759 arraySubscriptExpr()));
2760}
2761
2762TEST(ArraySubscriptMatchers, ArrayIndex) {
2763 EXPECT_TRUE(matches(
2764 "int i[2]; void f() { i[1] = 1; }",
2765 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2766 EXPECT_TRUE(matches(
2767 "int i[2]; void f() { 1[i] = 1; }",
2768 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2769 EXPECT_TRUE(notMatches(
2770 "int i[2]; void f() { i[1] = 1; }",
2771 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2772}
2773
2774TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2775 EXPECT_TRUE(matches(
2776 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002777 arraySubscriptExpr(hasBase(implicitCastExpr(
2778 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002779}
2780
Manuel Klimek04616e42012-07-06 05:48:52 +00002781TEST(Matcher, HasNameSupportsNamespaces) {
2782 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002783 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002784 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002785 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002786 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002787 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002788 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002789 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002790 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002791 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002792 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002793 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002794 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002795 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002796 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002797 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002798 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002799 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002800 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002801 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002802 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002803 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002804 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002805 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002806}
2807
2808TEST(Matcher, HasNameSupportsOuterClasses) {
2809 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002810 matches("class A { class B { class C; }; };",
2811 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002812 EXPECT_TRUE(
2813 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002814 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002815 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002816 matches("class A { class B { class C; }; };",
2817 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002818 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002819 matches("class A { class B { class C; }; };",
2820 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002821 EXPECT_TRUE(
2822 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002823 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002824 EXPECT_TRUE(
2825 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002826 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002827 EXPECT_TRUE(
2828 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002829 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002830 EXPECT_TRUE(
2831 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002832 recordDecl(hasName("::C"))));
2833 EXPECT_TRUE(
2834 notMatches("class A { class B { class C; }; };",
2835 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002836 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002837 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002838 EXPECT_TRUE(
2839 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002840 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002841}
2842
Samuel Benzaquen8e566f32016-02-05 18:29:24 +00002843TEST(Matcher, HasNameSupportsInlinedNamespaces) {
2844 std::string code = "namespace a { inline namespace b { class C; } }";
2845 EXPECT_TRUE(matches(code, recordDecl(hasName("a::b::C"))));
2846 EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
2847 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::b::C"))));
2848 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
2849}
2850
2851TEST(Matcher, HasNameSupportsAnonymousNamespaces) {
2852 std::string code = "namespace a { namespace { class C; } }";
2853 EXPECT_TRUE(
2854 matches(code, recordDecl(hasName("a::(anonymous namespace)::C"))));
2855 EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
2856 EXPECT_TRUE(
2857 matches(code, recordDecl(hasName("::a::(anonymous namespace)::C"))));
2858 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
2859}
2860
2861TEST(Matcher, HasNameSupportsAnonymousOuterClasses) {
2862 EXPECT_TRUE(matches("class A { class { class C; } x; };",
2863 recordDecl(hasName("A::(anonymous class)::C"))));
2864 EXPECT_TRUE(matches("class A { class { class C; } x; };",
2865 recordDecl(hasName("::A::(anonymous class)::C"))));
2866 EXPECT_FALSE(matches("class A { class { class C; } x; };",
2867 recordDecl(hasName("::A::C"))));
2868 EXPECT_TRUE(matches("class A { struct { class C; } x; };",
2869 recordDecl(hasName("A::(anonymous struct)::C"))));
2870 EXPECT_TRUE(matches("class A { struct { class C; } x; };",
2871 recordDecl(hasName("::A::(anonymous struct)::C"))));
2872 EXPECT_FALSE(matches("class A { struct { class C; } x; };",
2873 recordDecl(hasName("::A::C"))));
2874}
2875
2876TEST(Matcher, HasNameSupportsFunctionScope) {
2877 std::string code =
2878 "namespace a { void F(int a) { struct S { int m; }; int i; } }";
2879 EXPECT_TRUE(matches(code, varDecl(hasName("i"))));
2880 EXPECT_FALSE(matches(code, varDecl(hasName("F()::i"))));
2881
2882 EXPECT_TRUE(matches(code, fieldDecl(hasName("m"))));
2883 EXPECT_TRUE(matches(code, fieldDecl(hasName("S::m"))));
2884 EXPECT_TRUE(matches(code, fieldDecl(hasName("F(int)::S::m"))));
2885 EXPECT_TRUE(matches(code, fieldDecl(hasName("a::F(int)::S::m"))));
2886 EXPECT_TRUE(matches(code, fieldDecl(hasName("::a::F(int)::S::m"))));
2887}
2888
Samuel Benzaquen922bef42016-02-22 21:13:02 +00002889TEST(Matcher, HasAnyName) {
2890 const std::string Code = "namespace a { namespace b { class C; } }";
2891
2892 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "a::b::C"))));
2893 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("a::b::C", "XX"))));
2894 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX::C", "a::b::C"))));
2895 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "C"))));
2896
2897 EXPECT_TRUE(notMatches(Code, recordDecl(hasAnyName("::C", "::b::C"))));
2898 EXPECT_TRUE(
2899 matches(Code, recordDecl(hasAnyName("::C", "::b::C", "::a::b::C"))));
2900}
2901
Manuel Klimek04616e42012-07-06 05:48:52 +00002902TEST(Matcher, IsDefinition) {
2903 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002904 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002905 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2906 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2907
2908 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002909 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002910 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2911 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2912
2913 DeclarationMatcher DefinitionOfMethodA =
Aaron Ballman512fb642015-09-17 13:30:52 +00002914 cxxMethodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002915 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2916 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2917}
2918
2919TEST(Matcher, OfClass) {
Aaron Ballman512fb642015-09-17 13:30:52 +00002920 StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002921 ofClass(hasName("X")))));
2922
2923 EXPECT_TRUE(
2924 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2925 EXPECT_TRUE(
2926 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2927 Constructor));
2928 EXPECT_TRUE(
2929 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2930 Constructor));
2931}
2932
2933TEST(Matcher, VisitsTemplateInstantiations) {
2934 EXPECT_TRUE(matches(
2935 "class A { public: void x(); };"
2936 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002937 "void f() { B<A> b; b.y(); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00002938 callExpr(callee(cxxMethodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002939
2940 EXPECT_TRUE(matches(
2941 "class A { public: void x(); };"
2942 "class C {"
2943 " public:"
2944 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2945 "};"
2946 "void f() {"
2947 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002948 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00002949 recordDecl(hasName("C"), hasDescendant(callExpr(
2950 callee(cxxMethodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002951}
2952
Daniel Jasper1dad1832012-07-10 20:20:19 +00002953TEST(Matcher, HandlesNullQualTypes) {
2954 // FIXME: Add a Type matcher so we can replace uses of this
2955 // variable with Type(True())
2956 const TypeMatcher AnyType = anything();
2957
2958 // We don't really care whether this matcher succeeds; we're testing that
2959 // it completes without crashing.
2960 EXPECT_TRUE(matches(
2961 "struct A { };"
2962 "template <typename T>"
2963 "void f(T t) {"
2964 " T local_t(t /* this becomes a null QualType in the AST */);"
2965 "}"
2966 "void g() {"
2967 " f(0);"
2968 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002969 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002970 anyOf(
2971 TypeMatcher(hasDeclaration(anything())),
2972 pointsTo(AnyType),
2973 references(AnyType)
2974 // Other QualType matchers should go here.
2975 ))))));
2976}
2977
Manuel Klimek04616e42012-07-06 05:48:52 +00002978// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002979AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002980 // Make sure all special variables are used: node, match_finder,
2981 // bound_nodes_builder, and the parameter named 'AMatcher'.
2982 return AMatcher.matches(Node, Finder, Builder);
2983}
2984
2985TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002986 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002987
2988 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002989 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002990
2991 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002992 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002993
2994 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002995 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002996}
2997
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +00002998AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
2999 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
3000 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003001 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00003002 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00003003 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
3004 ASTMatchFinder::BK_First);
3005}
3006
3007TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003008 DeclarationMatcher HasClassB =
3009 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00003010
3011 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003012 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00003013
3014 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003015 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00003016
3017 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003018 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00003019
3020 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003021 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00003022
3023 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
3024}
3025
3026TEST(For, FindsForLoops) {
3027 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
3028 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00003029 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
3030 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00003031 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003032}
3033
Daniel Jasper4e566c42012-07-12 08:50:38 +00003034TEST(For, ForLoopInternals) {
3035 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
3036 forStmt(hasCondition(anything()))));
3037 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
3038 forStmt(hasLoopInit(anything()))));
3039}
3040
Alexander Kornienko9b539e12014-02-05 16:35:08 +00003041TEST(For, ForRangeLoopInternals) {
3042 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003043 cxxForRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00003044 EXPECT_TRUE(matches(
3045 "void f(){ int a[] {1, 2}; for (int i : a); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003046 cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00003047}
3048
Daniel Jasper4e566c42012-07-12 08:50:38 +00003049TEST(For, NegativeForLoopInternals) {
3050 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003051 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00003052 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
3053 forStmt(hasLoopInit(anything()))));
3054}
3055
Manuel Klimek04616e42012-07-06 05:48:52 +00003056TEST(For, ReportsNoFalsePositives) {
3057 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
3058 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
3059}
3060
3061TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003062 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
3063 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
3064 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003065}
3066
3067TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
3068 // It's not a compound statement just because there's "{}" in the source
3069 // text. This is an AST search, not grep.
3070 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003071 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003072 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003073 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003074}
3075
Daniel Jasper4e566c42012-07-12 08:50:38 +00003076TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003077 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003078 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003079 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003080 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00003081 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003082 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00003083 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003084 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00003085 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003086 cxxForRangeStmt(hasBody(compoundStmt()))));
Aaron Ballman2b6963f2016-01-20 16:26:48 +00003087 EXPECT_TRUE(matches("void f() {}", functionDecl(hasBody(compoundStmt()))));
3088 EXPECT_TRUE(notMatches("void f();", functionDecl(hasBody(compoundStmt()))));
3089 EXPECT_TRUE(matches("void f(); void f() {}",
3090 functionDecl(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003091}
3092
3093TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
3094 // The simplest case: every compound statement is in a function
3095 // definition, and the function body itself must be a compound
3096 // statement.
3097 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003098 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003099}
3100
3101TEST(HasAnySubstatement, IsNotRecursive) {
3102 // It's really "has any immediate substatement".
3103 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003104 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003105}
3106
3107TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
3108 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003109 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003110}
3111
3112TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
3113 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003114 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003115}
3116
3117TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
3118 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003119 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003120 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003121 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003122}
3123
3124TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
3125 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003126 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003127 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003128 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003129 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003130 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003131}
3132
3133TEST(StatementCountIs, WorksWithMultipleStatements) {
3134 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003135 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003136}
3137
3138TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
3139 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003140 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003141 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003142 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003143 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003144 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003145 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003146 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003147}
3148
3149TEST(Member, WorksInSimplestCase) {
3150 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003151 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003152}
3153
3154TEST(Member, DoesNotMatchTheBaseExpression) {
3155 // Don't pick out the wrong part of the member expression, this should
3156 // be checking the member (name) only.
3157 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003158 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003159}
3160
3161TEST(Member, MatchesInMemberFunctionCall) {
3162 EXPECT_TRUE(matches("void f() {"
3163 " struct { void first() {}; } s;"
3164 " s.first();"
3165 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003166 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003167}
3168
Daniel Jasperb0c7b612012-10-23 15:46:39 +00003169TEST(Member, MatchesMember) {
3170 EXPECT_TRUE(matches(
3171 "struct A { int i; }; void f() { A a; a.i = 2; }",
3172 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
3173 EXPECT_TRUE(notMatches(
3174 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
3175 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
3176}
3177
Daniel Jasper639522c2013-02-25 12:02:08 +00003178TEST(Member, UnderstandsAccess) {
3179 EXPECT_TRUE(matches(
3180 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
3181 EXPECT_TRUE(notMatches(
3182 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
3183 EXPECT_TRUE(notMatches(
3184 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
3185
3186 EXPECT_TRUE(notMatches(
3187 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
3188 EXPECT_TRUE(notMatches(
3189 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
3190 EXPECT_TRUE(matches(
3191 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
3192
3193 EXPECT_TRUE(notMatches(
3194 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
3195 EXPECT_TRUE(matches("class A { protected: int i; };",
3196 fieldDecl(isProtected(), hasName("i"))));
3197 EXPECT_TRUE(notMatches(
3198 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
3199
3200 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
3201 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
3202 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
3203 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
3204}
3205
Dmitri Gribenko06963042012-08-18 00:29:27 +00003206TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00003207 // Fails in C++11 mode
3208 EXPECT_TRUE(matchesConditionally(
3209 "namespace std { typedef typeof(sizeof(int)) size_t; }"
3210 "class X { void *operator new(std::size_t); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003211 cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00003212
3213 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003214 cxxMethodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00003215
Daniel Jasper5901e472012-10-01 13:40:41 +00003216 // Fails in C++11 mode
3217 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003218 "namespace std { typedef typeof(sizeof(int)) size_t; }"
3219 "class X { void operator delete[](void*, std::size_t); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003220 cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00003221}
3222
Manuel Klimek04616e42012-07-06 05:48:52 +00003223TEST(HasObjectExpression, DoesNotMatchMember) {
3224 EXPECT_TRUE(notMatches(
3225 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003226 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003227}
3228
3229TEST(HasObjectExpression, MatchesBaseOfVariable) {
3230 EXPECT_TRUE(matches(
3231 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003232 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003233 EXPECT_TRUE(matches(
3234 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003235 memberExpr(hasObjectExpression(
3236 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003237}
3238
3239TEST(HasObjectExpression,
3240 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
3241 EXPECT_TRUE(matches(
3242 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003243 memberExpr(hasObjectExpression(
3244 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003245 EXPECT_TRUE(matches(
3246 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003247 memberExpr(hasObjectExpression(
3248 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003249}
3250
3251TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003252 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
3253 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
3254 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
3255 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003256}
3257
3258TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003259 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003260}
3261
Aaron Ballman6290fc92015-11-23 17:09:24 +00003262TEST(IsVolatileQualified, QualifiersMatch) {
3263 EXPECT_TRUE(matches("volatile int i = 42;",
3264 varDecl(hasType(isVolatileQualified()))));
3265 EXPECT_TRUE(notMatches("volatile int *i;",
3266 varDecl(hasType(isVolatileQualified()))));
3267 EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
3268 varDecl(hasType(isVolatileQualified()))));
3269}
3270
Manuel Klimek04616e42012-07-06 05:48:52 +00003271TEST(IsConstQualified, MatchesConstInt) {
3272 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003273 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003274}
3275
3276TEST(IsConstQualified, MatchesConstPointer) {
3277 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003278 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003279}
3280
3281TEST(IsConstQualified, MatchesThroughTypedef) {
3282 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003283 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003284 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003285 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003286}
3287
3288TEST(IsConstQualified, DoesNotMatchInappropriately) {
3289 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003290 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003291 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003292 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003293}
3294
Sam Panzer80c13772012-08-16 16:58:10 +00003295TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003296 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
3297 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
3298 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
3299 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003300}
3301TEST(CastExpression, MatchesImplicitCasts) {
3302 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00003303 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003304 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00003305 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003306}
3307
3308TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00003309 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
3310 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
3311 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
3312 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00003313}
3314
Manuel Klimek04616e42012-07-06 05:48:52 +00003315TEST(ReinterpretCast, MatchesSimpleCase) {
3316 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003317 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003318}
3319
3320TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003321 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003322 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003323 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003324 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003325 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003326 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3327 "B b;"
3328 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003329 cxxReinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003330}
3331
3332TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003333 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003334 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003335 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003336}
3337
3338TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003339 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00003340 EXPECT_TRUE(
3341 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003342 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003343 EXPECT_TRUE(
3344 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003345 cxxFunctionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003346}
3347
3348TEST(DynamicCast, MatchesSimpleCase) {
3349 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
3350 "B b;"
3351 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003352 cxxDynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003353}
3354
3355TEST(StaticCast, MatchesSimpleCase) {
3356 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Aaron Ballman512fb642015-09-17 13:30:52 +00003357 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003358}
3359
3360TEST(StaticCast, DoesNotMatchOtherCasts) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003361 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003362 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003363 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003364 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003365 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003366 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
3367 "B b;"
3368 "D* p = dynamic_cast<D*>(&b);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003369 cxxStaticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003370}
3371
Daniel Jasper417f7762012-09-18 13:36:17 +00003372TEST(CStyleCast, MatchesSimpleCase) {
3373 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
3374}
3375
3376TEST(CStyleCast, DoesNotMatchOtherCasts) {
3377 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
3378 "char q, *r = const_cast<char*>(&q);"
3379 "void* s = reinterpret_cast<char*>(&s);"
3380 "struct B { virtual ~B() {} }; struct D : B {};"
3381 "B b;"
3382 "D* t = dynamic_cast<D*>(&b);",
3383 cStyleCastExpr()));
3384}
3385
Manuel Klimek04616e42012-07-06 05:48:52 +00003386TEST(HasDestinationType, MatchesSimpleCase) {
3387 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Aaron Ballman512fb642015-09-17 13:30:52 +00003388 cxxStaticCastExpr(hasDestinationType(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003389 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003390}
3391
Sam Panzer80c13772012-08-16 16:58:10 +00003392TEST(HasImplicitDestinationType, MatchesSimpleCase) {
3393 // This test creates an implicit const cast.
3394 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003395 implicitCastExpr(
3396 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003397 // This test creates an implicit array-to-pointer cast.
3398 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003399 implicitCastExpr(hasImplicitDestinationType(
3400 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003401}
3402
3403TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
3404 // This test creates an implicit cast from int to char.
3405 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003406 implicitCastExpr(hasImplicitDestinationType(
3407 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003408 // This test creates an implicit array-to-pointer cast.
3409 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003410 implicitCastExpr(hasImplicitDestinationType(
3411 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003412}
3413
3414TEST(ImplicitCast, MatchesSimpleCase) {
3415 // This test creates an implicit const cast.
3416 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003417 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003418 // This test creates an implicit cast from int to char.
3419 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003420 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003421 // This test creates an implicit array-to-pointer cast.
3422 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003423 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003424}
3425
3426TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003427 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00003428 // are present, and that it ignores explicit and paren casts.
3429
3430 // These two test cases have no casts.
3431 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003432 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003433 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003434 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003435
3436 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003437 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003438 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003439 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003440
3441 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003442 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00003443}
3444
3445TEST(IgnoringImpCasts, MatchesImpCasts) {
3446 // This test checks that ignoringImpCasts matches when implicit casts are
3447 // present and its inner matcher alone does not match.
3448 // Note that this test creates an implicit const cast.
3449 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003450 varDecl(hasInitializer(ignoringImpCasts(
3451 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003452 // This test creates an implict cast from int to char.
3453 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003454 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003455 integerLiteral(equals(0)))))));
3456}
3457
3458TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
3459 // These tests verify that ignoringImpCasts does not match if the inner
3460 // matcher does not match.
3461 // Note that the first test creates an implicit const cast.
3462 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003463 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003464 unless(anything()))))));
3465 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003466 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003467 unless(anything()))))));
3468
3469 // These tests verify that ignoringImplictCasts does not look through explicit
3470 // casts or parentheses.
3471 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003472 varDecl(hasInitializer(ignoringImpCasts(
3473 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003474 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003475 varDecl(hasInitializer(ignoringImpCasts(
3476 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003477 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003478 varDecl(hasInitializer(ignoringImpCasts(
3479 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003480 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003481 varDecl(hasInitializer(ignoringImpCasts(
3482 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003483}
3484
3485TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3486 // This test verifies that expressions that do not have implicit casts
3487 // still match the inner matcher.
3488 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003489 varDecl(hasInitializer(ignoringImpCasts(
3490 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003491}
3492
3493TEST(IgnoringParenCasts, MatchesParenCasts) {
3494 // This test checks that ignoringParenCasts matches when parentheses and/or
3495 // casts are present and its inner matcher alone does not match.
3496 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003497 varDecl(hasInitializer(ignoringParenCasts(
3498 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003499 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003500 varDecl(hasInitializer(ignoringParenCasts(
3501 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003502
3503 // This test creates an implict cast from int to char in addition to the
3504 // parentheses.
3505 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003506 varDecl(hasInitializer(ignoringParenCasts(
3507 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003508
3509 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003510 varDecl(hasInitializer(ignoringParenCasts(
3511 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003512 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003513 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003514 integerLiteral(equals(0)))))));
3515}
3516
3517TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3518 // This test verifies that expressions that do not have any casts still match.
3519 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003520 varDecl(hasInitializer(ignoringParenCasts(
3521 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003522}
3523
3524TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3525 // These tests verify that ignoringImpCasts does not match if the inner
3526 // matcher does not match.
3527 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003528 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003529 unless(anything()))))));
3530
3531 // This test creates an implicit cast from int to char in addition to the
3532 // parentheses.
3533 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003534 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003535 unless(anything()))))));
3536
3537 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003538 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003539 unless(anything()))))));
3540}
3541
3542TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3543 // This test checks that ignoringParenAndImpCasts matches when
3544 // parentheses and/or implicit casts are present and its inner matcher alone
3545 // does not match.
3546 // Note that this test creates an implicit const cast.
3547 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003548 varDecl(hasInitializer(ignoringParenImpCasts(
3549 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003550 // This test creates an implicit cast from int to char.
3551 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003552 varDecl(hasInitializer(ignoringParenImpCasts(
3553 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003554}
3555
3556TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3557 // This test verifies that expressions that do not have parentheses or
3558 // implicit casts still match.
3559 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003560 varDecl(hasInitializer(ignoringParenImpCasts(
3561 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003562 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003563 varDecl(hasInitializer(ignoringParenImpCasts(
3564 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003565}
3566
3567TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3568 // These tests verify that ignoringParenImpCasts does not match if
3569 // the inner matcher does not match.
3570 // This test creates an implicit cast.
3571 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003572 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003573 unless(anything()))))));
3574 // These tests verify that ignoringParenAndImplictCasts does not look
3575 // through explicit casts.
3576 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003577 varDecl(hasInitializer(ignoringParenImpCasts(
3578 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003579 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003580 varDecl(hasInitializer(ignoringParenImpCasts(
3581 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003582 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003583 varDecl(hasInitializer(ignoringParenImpCasts(
3584 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003585}
3586
Manuel Klimeke9235692012-07-25 10:02:02 +00003587TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003588 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3589 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003590 implicitCastExpr(
Aaron Ballman512fb642015-09-17 13:30:52 +00003591 hasSourceExpression(cxxConstructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003592}
3593
Manuel Klimeke9235692012-07-25 10:02:02 +00003594TEST(HasSourceExpression, MatchesExplicitCasts) {
3595 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003596 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003597 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003598 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003599}
3600
Manuel Klimek04616e42012-07-06 05:48:52 +00003601TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003602 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003603}
3604
3605TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003606 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003607}
3608
3609TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003610 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003611}
3612
3613TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003614 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003615}
3616
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003617TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3618 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3619 "const Foo f = Foo();",
3620 varDecl(hasInitializer(exprWithCleanups()))));
3621 EXPECT_FALSE(matches("struct Foo { };"
3622 "const Foo f = Foo();",
3623 varDecl(hasInitializer(exprWithCleanups()))));
3624}
3625
Daniel Jasper1dad1832012-07-10 20:20:19 +00003626TEST(InitListExpression, MatchesInitListExpression) {
3627 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3628 initListExpr(hasType(asString("int [2]")))));
3629 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003630 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003631 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3632 "void f();"
3633 "S s[1] = { &f };",
3634 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper774e6b52015-02-04 14:29:47 +00003635 EXPECT_TRUE(
3636 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003637}
3638
3639TEST(UsingDeclaration, MatchesUsingDeclarations) {
3640 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3641 usingDecl()));
3642}
3643
3644TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3645 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3646 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3647}
3648
3649TEST(UsingDeclaration, MatchesSpecificTarget) {
3650 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3651 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003652 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003653 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3654 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003655 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003656}
3657
3658TEST(UsingDeclaration, ThroughUsingDeclaration) {
3659 EXPECT_TRUE(matches(
3660 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003661 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003662 EXPECT_TRUE(notMatches(
3663 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003664 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003665}
3666
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003667TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3668 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3669 usingDirectiveDecl()));
3670 EXPECT_FALSE(
3671 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3672}
3673
Sam Panzerd624bfb2012-08-16 17:20:59 +00003674TEST(SingleDecl, IsSingleDecl) {
3675 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003676 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003677 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3678 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3679 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3680 SingleDeclStmt));
3681}
3682
3683TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003684 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003685
3686 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003687 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003688 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003689 declStmt(containsDeclaration(0, MatchesInit),
3690 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003691 unsigned WrongIndex = 42;
3692 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003693 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003694 MatchesInit))));
3695}
3696
3697TEST(DeclCount, DeclCountIsCorrect) {
3698 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003699 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003700 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003701 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003702 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003703 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003704}
3705
Manuel Klimek04616e42012-07-06 05:48:52 +00003706TEST(While, MatchesWhileLoops) {
3707 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3708 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3709 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3710}
3711
3712TEST(Do, MatchesDoLoops) {
3713 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3714 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3715}
3716
3717TEST(Do, DoesNotMatchWhileLoops) {
3718 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3719}
3720
3721TEST(SwitchCase, MatchesCase) {
3722 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3723 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3724 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3725 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3726}
3727
Daniel Jasper87c3d362012-09-20 14:12:57 +00003728TEST(SwitchCase, MatchesSwitch) {
3729 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3730 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3731 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3732 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3733}
3734
Peter Collingbourne3154a102013-05-10 11:52:02 +00003735TEST(SwitchCase, MatchesEachCase) {
3736 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3737 switchStmt(forEachSwitchCase(caseStmt()))));
3738 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3739 switchStmt(forEachSwitchCase(caseStmt()))));
3740 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3741 switchStmt(forEachSwitchCase(caseStmt()))));
3742 EXPECT_TRUE(notMatches(
3743 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3744 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3745 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3746 switchStmt(forEachSwitchCase(
3747 caseStmt(hasCaseConstant(integerLiteral()))))));
3748 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3749 switchStmt(forEachSwitchCase(
3750 caseStmt(hasCaseConstant(integerLiteral()))))));
3751 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3752 switchStmt(forEachSwitchCase(
3753 caseStmt(hasCaseConstant(integerLiteral()))))));
3754 EXPECT_TRUE(matchAndVerifyResultTrue(
3755 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3756 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3757 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3758}
3759
Manuel Klimekba46fc02013-07-19 11:50:54 +00003760TEST(ForEachConstructorInitializer, MatchesInitializers) {
3761 EXPECT_TRUE(matches(
3762 "struct X { X() : i(42), j(42) {} int i, j; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003763 cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer()))));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003764}
3765
Daniel Jasper87c3d362012-09-20 14:12:57 +00003766TEST(ExceptionHandling, SimpleCases) {
Aaron Ballman512fb642015-09-17 13:30:52 +00003767 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
3768 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
3769 EXPECT_TRUE(
3770 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003771 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003772 cxxThrowExpr()));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003773 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003774 cxxThrowExpr()));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003775 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003776 cxxCatchStmt(isCatchAll())));
Aaron Ballman9b869aa2015-07-02 12:53:22 +00003777 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
Aaron Ballman512fb642015-09-17 13:30:52 +00003778 cxxCatchStmt(isCatchAll())));
Aaron Ballman39918462015-07-15 17:11:21 +00003779 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
3780 varDecl(isExceptionVariable())));
3781 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
3782 varDecl(isExceptionVariable())));
Daniel Jasper87c3d362012-09-20 14:12:57 +00003783}
3784
Aaron Ballmane8295d72016-01-20 16:17:39 +00003785TEST(ParenExpression, SimpleCases) {
3786 EXPECT_TRUE(matches("int i = (3);", parenExpr()));
3787 EXPECT_TRUE(matches("int i = (3 + 7);", parenExpr()));
3788 EXPECT_TRUE(notMatches("int i = 3;", parenExpr()));
3789 EXPECT_TRUE(notMatches("int foo() { return 1; }; int a = foo();",
3790 parenExpr()));
3791}
3792
Manuel Klimek04616e42012-07-06 05:48:52 +00003793TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3794 EXPECT_TRUE(notMatches(
3795 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003796 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003797 EXPECT_TRUE(notMatches(
3798 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003799 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003800}
3801
3802TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3803 EXPECT_TRUE(matches(
3804 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003805 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003806}
3807
3808TEST(ForEach, BindsOneNode) {
3809 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003810 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003811 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003812}
3813
3814TEST(ForEach, BindsMultipleNodes) {
3815 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003816 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003817 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003818}
3819
3820TEST(ForEach, BindsRecursiveCombinations) {
3821 EXPECT_TRUE(matchAndVerifyResultTrue(
3822 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003823 recordDecl(hasName("C"),
3824 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003825 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003826}
3827
3828TEST(ForEachDescendant, BindsOneNode) {
3829 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003830 recordDecl(hasName("C"),
3831 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003832 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003833}
3834
Daniel Jasper94a56852012-11-16 18:39:22 +00003835TEST(ForEachDescendant, NestedForEachDescendant) {
3836 DeclarationMatcher m = recordDecl(
3837 isDefinition(), decl().bind("x"), hasName("C"));
3838 EXPECT_TRUE(matchAndVerifyResultTrue(
3839 "class A { class B { class C {}; }; };",
3840 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3841 new VerifyIdIsBoundTo<Decl>("x", "C")));
3842
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003843 // Check that a partial match of 'm' that binds 'x' in the
3844 // first part of anyOf(m, anything()) will not overwrite the
3845 // binding created by the earlier binding in the hasDescendant.
3846 EXPECT_TRUE(matchAndVerifyResultTrue(
3847 "class A { class B { class C {}; }; };",
3848 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3849 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003850}
3851
Manuel Klimek04616e42012-07-06 05:48:52 +00003852TEST(ForEachDescendant, BindsMultipleNodes) {
3853 EXPECT_TRUE(matchAndVerifyResultTrue(
3854 "class C { class D { int x; int y; }; "
3855 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003856 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003857 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003858}
3859
3860TEST(ForEachDescendant, BindsRecursiveCombinations) {
3861 EXPECT_TRUE(matchAndVerifyResultTrue(
3862 "class C { class D { "
3863 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003864 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3865 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003866 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003867}
3868
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003869TEST(ForEachDescendant, BindsCombinations) {
3870 EXPECT_TRUE(matchAndVerifyResultTrue(
3871 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3872 "(true) {} }",
3873 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3874 forEachDescendant(whileStmt().bind("while"))),
3875 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3876}
3877
3878TEST(Has, DoesNotDeleteBindings) {
3879 EXPECT_TRUE(matchAndVerifyResultTrue(
3880 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3881 new VerifyIdIsBoundTo<Decl>("x", 1)));
3882}
3883
3884TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3885 // Those matchers cover all the cases where an inner matcher is called
3886 // and there is not a 1:1 relationship between the match of the outer
3887 // matcher and the match of the inner matcher.
3888 // The pattern to look for is:
3889 // ... return InnerMatcher.matches(...); ...
3890 // In which case no special handling is needed.
3891 //
3892 // On the other hand, if there are multiple alternative matches
3893 // (for example forEach*) or matches might be discarded (for example has*)
3894 // the implementation must make sure that the discarded matches do not
3895 // affect the bindings.
3896 // When new such matchers are added, add a test here that:
3897 // - matches a simple node, and binds it as the first thing in the matcher:
3898 // recordDecl(decl().bind("x"), hasName("X")))
3899 // - uses the matcher under test afterwards in a way that not the first
3900 // alternative is matched; for anyOf, that means the first branch
3901 // would need to return false; for hasAncestor, it means that not
3902 // the direct parent matches the inner matcher.
3903
3904 EXPECT_TRUE(matchAndVerifyResultTrue(
3905 "class X { int y; };",
3906 recordDecl(
3907 recordDecl().bind("x"), hasName("::X"),
3908 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3909 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3910 EXPECT_TRUE(matchAndVerifyResultTrue(
3911 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3912 anyOf(unless(anything()), anything())),
3913 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3914 EXPECT_TRUE(matchAndVerifyResultTrue(
3915 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3916 classTemplateSpecializationDecl(
3917 decl().bind("x"),
3918 hasAnyTemplateArgument(refersToType(asString("int")))),
3919 new VerifyIdIsBoundTo<Decl>("x", 1)));
3920 EXPECT_TRUE(matchAndVerifyResultTrue(
3921 "class X { void f(); void g(); };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003922 cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003923 new VerifyIdIsBoundTo<Decl>("x", 1)));
3924 EXPECT_TRUE(matchAndVerifyResultTrue(
3925 "class X { X() : a(1), b(2) {} double a; int b; };",
3926 recordDecl(decl().bind("x"),
Aaron Ballman512fb642015-09-17 13:30:52 +00003927 has(cxxConstructorDecl(
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003928 hasAnyConstructorInitializer(forField(hasName("b")))))),
3929 new VerifyIdIsBoundTo<Decl>("x", 1)));
3930 EXPECT_TRUE(matchAndVerifyResultTrue(
3931 "void x(int, int) { x(0, 42); }",
3932 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3933 new VerifyIdIsBoundTo<Expr>("x", 1)));
3934 EXPECT_TRUE(matchAndVerifyResultTrue(
3935 "void x(int, int y) {}",
3936 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3937 new VerifyIdIsBoundTo<Decl>("x", 1)));
3938 EXPECT_TRUE(matchAndVerifyResultTrue(
3939 "void x() { return; if (true) {} }",
3940 functionDecl(decl().bind("x"),
3941 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3942 new VerifyIdIsBoundTo<Decl>("x", 1)));
3943 EXPECT_TRUE(matchAndVerifyResultTrue(
3944 "namespace X { void b(int); void b(); }"
3945 "using X::b;",
3946 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3947 functionDecl(parameterCountIs(1))))),
3948 new VerifyIdIsBoundTo<Decl>("x", 1)));
3949 EXPECT_TRUE(matchAndVerifyResultTrue(
3950 "class A{}; class B{}; class C : B, A {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003951 cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003952 new VerifyIdIsBoundTo<Decl>("x", 1)));
3953 EXPECT_TRUE(matchAndVerifyResultTrue(
3954 "class A{}; typedef A B; typedef A C; typedef A D;"
3955 "class E : A {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00003956 cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")),
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003957 new VerifyIdIsBoundTo<Decl>("x", 1)));
3958 EXPECT_TRUE(matchAndVerifyResultTrue(
3959 "class A { class B { void f() {} }; };",
3960 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3961 new VerifyIdIsBoundTo<Decl>("x", 1)));
3962 EXPECT_TRUE(matchAndVerifyResultTrue(
3963 "template <typename T> struct A { struct B {"
3964 " void f() { if(true) {} }"
3965 "}; };"
3966 "void t() { A<int>::B b; b.f(); }",
3967 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3968 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3969 EXPECT_TRUE(matchAndVerifyResultTrue(
3970 "class A {};",
3971 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3972 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003973 EXPECT_TRUE(matchAndVerifyResultTrue(
3974 "class A { A() : s(), i(42) {} const char *s; int i; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00003975 cxxConstructorDecl(hasName("::A::A"), decl().bind("x"),
3976 forEachConstructorInitializer(forField(hasName("i")))),
Manuel Klimekba46fc02013-07-19 11:50:54 +00003977 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003978}
3979
Daniel Jasper33806cd2012-11-11 22:14:55 +00003980TEST(ForEachDescendant, BindsCorrectNodes) {
3981 EXPECT_TRUE(matchAndVerifyResultTrue(
3982 "class C { void f(); int i; };",
3983 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3984 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3985 EXPECT_TRUE(matchAndVerifyResultTrue(
3986 "class C { void f() {} int i; };",
3987 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3988 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3989}
3990
Manuel Klimekabf43712013-02-04 10:59:20 +00003991TEST(FindAll, BindsNodeOnMatch) {
3992 EXPECT_TRUE(matchAndVerifyResultTrue(
3993 "class A {};",
3994 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3995 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3996}
3997
3998TEST(FindAll, BindsDescendantNodeOnMatch) {
3999 EXPECT_TRUE(matchAndVerifyResultTrue(
4000 "class A { int a; int b; };",
4001 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
4002 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
4003}
4004
4005TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
4006 EXPECT_TRUE(matchAndVerifyResultTrue(
4007 "class A { int a; int b; };",
4008 recordDecl(hasName("::A"),
4009 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
4010 fieldDecl().bind("v"))))),
4011 new VerifyIdIsBoundTo<Decl>("v", 3)));
4012
4013 EXPECT_TRUE(matchAndVerifyResultTrue(
4014 "class A { class B {}; class C {}; };",
4015 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
4016 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
4017}
4018
Manuel Klimek88b95872013-02-04 09:42:38 +00004019TEST(EachOf, TriggersForEachMatch) {
4020 EXPECT_TRUE(matchAndVerifyResultTrue(
4021 "class A { int a; int b; };",
4022 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
4023 has(fieldDecl(hasName("b")).bind("v")))),
4024 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
4025}
4026
4027TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
4028 EXPECT_TRUE(matchAndVerifyResultTrue(
4029 "class A { int a; int c; };",
4030 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
4031 has(fieldDecl(hasName("b")).bind("v")))),
4032 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
4033 EXPECT_TRUE(matchAndVerifyResultTrue(
4034 "class A { int c; int b; };",
4035 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
4036 has(fieldDecl(hasName("b")).bind("v")))),
4037 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
4038 EXPECT_TRUE(notMatches(
4039 "class A { int c; int d; };",
4040 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
4041 has(fieldDecl(hasName("b")).bind("v"))))));
4042}
Manuel Klimek04616e42012-07-06 05:48:52 +00004043
4044TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
4045 // Make sure that we can both match the class by name (::X) and by the type
4046 // the template was instantiated with (via a field).
4047
4048 EXPECT_TRUE(matches(
4049 "template <typename T> class X {}; class A {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004050 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00004051
4052 EXPECT_TRUE(matches(
4053 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004054 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004055 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00004056}
4057
4058TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
4059 EXPECT_TRUE(matches(
4060 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004061 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00004062 isTemplateInstantiation())));
4063}
4064
4065TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
4066 EXPECT_TRUE(matches(
4067 "template <typename T> class X { T t; }; class A {};"
4068 "template class X<A>;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004069 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004070 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00004071}
4072
4073TEST(IsTemplateInstantiation,
4074 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
4075 EXPECT_TRUE(matches(
4076 "template <typename T> class X {};"
4077 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004078 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00004079}
4080
4081TEST(IsTemplateInstantiation,
4082 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
4083 EXPECT_TRUE(matches(
4084 "class A {};"
4085 "class X {"
4086 " template <typename U> class Y { U u; };"
4087 " Y<A> y;"
4088 "};",
Aaron Ballman512fb642015-09-17 13:30:52 +00004089 cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00004090}
4091
4092TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
4093 // FIXME: Figure out whether this makes sense. It doesn't affect the
4094 // normal use case as long as the uppermost instantiation always is marked
4095 // as template instantiation, but it might be confusing as a predicate.
4096 EXPECT_TRUE(matches(
4097 "class A {};"
4098 "template <typename T> class X {"
4099 " template <typename U> class Y { U u; };"
4100 " Y<T> y;"
4101 "}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004102 cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00004103}
4104
4105TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
4106 EXPECT_TRUE(notMatches(
4107 "template <typename T> class X {}; class A {};"
4108 "template <> class X<A> {}; X<A> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004109 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00004110}
4111
4112TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
4113 EXPECT_TRUE(notMatches(
4114 "class A {}; class Y { A a; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00004115 cxxRecordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00004116}
4117
Benjamin Kramer7ab84762014-09-03 12:08:14 +00004118TEST(IsInstantiated, MatchesInstantiation) {
4119 EXPECT_TRUE(
4120 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00004121 cxxRecordDecl(isInstantiated())));
Benjamin Kramer7ab84762014-09-03 12:08:14 +00004122}
4123
4124TEST(IsInstantiated, NotMatchesDefinition) {
4125 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00004126 cxxRecordDecl(isInstantiated())));
Benjamin Kramer7ab84762014-09-03 12:08:14 +00004127}
4128
4129TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
4130 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
4131 "class Y { A<int> a; }; Y y;",
4132 declStmt(isInTemplateInstantiation())));
4133}
4134
4135TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
4136 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
4137 declStmt(isInTemplateInstantiation())));
4138}
4139
4140TEST(IsInstantiated, MatchesFunctionInstantiation) {
4141 EXPECT_TRUE(
4142 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
4143 functionDecl(isInstantiated())));
4144}
4145
4146TEST(IsInstantiated, NotMatchesFunctionDefinition) {
4147 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
4148 varDecl(isInstantiated())));
4149}
4150
4151TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
4152 EXPECT_TRUE(
4153 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
4154 declStmt(isInTemplateInstantiation())));
4155}
4156
4157TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
4158 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
4159 declStmt(isInTemplateInstantiation())));
4160}
4161
4162TEST(IsInTemplateInstantiation, Sharing) {
4163 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
4164 // FIXME: Node sharing is an implementation detail, exposing it is ugly
4165 // and makes the matcher behave in non-obvious ways.
4166 EXPECT_TRUE(notMatches(
4167 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
4168 Matcher));
4169 EXPECT_TRUE(matches(
4170 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
4171 Matcher));
4172}
4173
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004174TEST(IsExplicitTemplateSpecialization,
4175 DoesNotMatchPrimaryTemplate) {
4176 EXPECT_TRUE(notMatches(
4177 "template <typename T> class X {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00004178 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004179 EXPECT_TRUE(notMatches(
4180 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004181 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004182}
4183
4184TEST(IsExplicitTemplateSpecialization,
4185 DoesNotMatchExplicitTemplateInstantiations) {
4186 EXPECT_TRUE(notMatches(
4187 "template <typename T> class X {};"
4188 "template class X<int>; extern template class X<long>;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004189 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004190 EXPECT_TRUE(notMatches(
4191 "template <typename T> void f(T t) {}"
4192 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004193 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004194}
4195
4196TEST(IsExplicitTemplateSpecialization,
4197 DoesNotMatchImplicitTemplateInstantiations) {
4198 EXPECT_TRUE(notMatches(
4199 "template <typename T> class X {}; X<int> x;",
Aaron Ballman512fb642015-09-17 13:30:52 +00004200 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004201 EXPECT_TRUE(notMatches(
4202 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004203 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004204}
4205
4206TEST(IsExplicitTemplateSpecialization,
4207 MatchesExplicitTemplateSpecializations) {
4208 EXPECT_TRUE(matches(
4209 "template <typename T> class X {};"
4210 "template<> class X<int> {};",
Aaron Ballman512fb642015-09-17 13:30:52 +00004211 cxxRecordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004212 EXPECT_TRUE(matches(
4213 "template <typename T> void f(T t) {}"
4214 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00004215 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00004216}
4217
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004218TEST(HasAncenstor, MatchesDeclarationAncestors) {
4219 EXPECT_TRUE(matches(
4220 "class A { class B { class C {}; }; };",
4221 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
4222}
4223
4224TEST(HasAncenstor, FailsIfNoAncestorMatches) {
4225 EXPECT_TRUE(notMatches(
4226 "class A { class B { class C {}; }; };",
4227 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
4228}
4229
4230TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
4231 EXPECT_TRUE(matches(
4232 "class A { class B { void f() { C c; } class C {}; }; };",
4233 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
4234 hasAncestor(recordDecl(hasName("A"))))))));
4235}
4236
4237TEST(HasAncenstor, MatchesStatementAncestors) {
4238 EXPECT_TRUE(matches(
4239 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00004240 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004241}
4242
4243TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
4244 EXPECT_TRUE(matches(
4245 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00004246 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004247}
4248
4249TEST(HasAncestor, BindsRecursiveCombinations) {
4250 EXPECT_TRUE(matchAndVerifyResultTrue(
4251 "class C { class D { class E { class F { int y; }; }; }; };",
4252 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004253 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004254}
4255
4256TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
4257 EXPECT_TRUE(matchAndVerifyResultTrue(
4258 "class C { class D { class E { class F { int y; }; }; }; };",
4259 fieldDecl(hasAncestor(
4260 decl(
4261 hasDescendant(recordDecl(isDefinition(),
4262 hasAncestor(recordDecl())))
4263 ).bind("d")
4264 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004265 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004266}
4267
Manuel Klimekb64d6b72013-03-14 16:33:21 +00004268TEST(HasAncestor, MatchesClosestAncestor) {
4269 EXPECT_TRUE(matchAndVerifyResultTrue(
4270 "template <typename T> struct C {"
4271 " void f(int) {"
4272 " struct I { void g(T) { int x; } } i; i.g(42);"
4273 " }"
4274 "};"
4275 "template struct C<int>;",
4276 varDecl(hasName("x"),
4277 hasAncestor(functionDecl(hasParameter(
4278 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
4279 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
4280}
4281
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004282TEST(HasAncestor, MatchesInTemplateInstantiations) {
4283 EXPECT_TRUE(matches(
4284 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
4285 "A<int>::B::C a;",
4286 fieldDecl(hasType(asString("int")),
4287 hasAncestor(recordDecl(hasName("A"))))));
4288}
4289
4290TEST(HasAncestor, MatchesInImplicitCode) {
4291 EXPECT_TRUE(matches(
4292 "struct X {}; struct A { A() {} X x; };",
Aaron Ballman512fb642015-09-17 13:30:52 +00004293 cxxConstructorDecl(
Manuel Klimek3ca12c52012-09-07 09:26:10 +00004294 hasAnyConstructorInitializer(withInitializer(expr(
4295 hasAncestor(recordDecl(hasName("A")))))))));
4296}
4297
Daniel Jasper632aea92012-10-22 16:26:51 +00004298TEST(HasParent, MatchesOnlyParent) {
4299 EXPECT_TRUE(matches(
4300 "void f() { if (true) { int x = 42; } }",
4301 compoundStmt(hasParent(ifStmt()))));
4302 EXPECT_TRUE(notMatches(
4303 "void f() { for (;;) { int x = 42; } }",
4304 compoundStmt(hasParent(ifStmt()))));
4305 EXPECT_TRUE(notMatches(
4306 "void f() { if (true) for (;;) { int x = 42; } }",
4307 compoundStmt(hasParent(ifStmt()))));
4308}
4309
Manuel Klimekc844a462012-12-06 14:42:48 +00004310TEST(HasAncestor, MatchesAllAncestors) {
4311 EXPECT_TRUE(matches(
4312 "template <typename T> struct C { static void f() { 42; } };"
4313 "void t() { C<int>::f(); }",
4314 integerLiteral(
4315 equals(42),
Aaron Ballman512fb642015-09-17 13:30:52 +00004316 allOf(
4317 hasAncestor(cxxRecordDecl(isTemplateInstantiation())),
4318 hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation())))))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004319}
4320
Nico Weberc4acee32016-01-22 15:11:54 +00004321TEST(HasAncestor, ImplicitArrayCopyCtorDeclRefExpr) {
4322 EXPECT_TRUE(matches("struct MyClass {\n"
4323 " int c[1];\n"
4324 " static MyClass Create() { return MyClass(); }\n"
4325 "};",
4326 declRefExpr(to(decl(hasAncestor(decl()))))));
4327}
4328
Nico Weber7b837f52016-01-28 19:25:00 +00004329TEST(HasAncestor, AnonymousUnionMemberExpr) {
4330 EXPECT_TRUE(matches("int F() {\n"
4331 " union { int i; };\n"
4332 " return i;\n"
4333 "}\n",
4334 memberExpr(member(hasAncestor(decl())))));
4335 EXPECT_TRUE(matches("void f() {\n"
4336 " struct {\n"
4337 " struct { int a; int b; };\n"
4338 " } s;\n"
4339 " s.a = 4;\n"
4340 "}\n",
4341 memberExpr(member(hasAncestor(decl())))));
4342 EXPECT_TRUE(matches("void f() {\n"
4343 " struct {\n"
4344 " struct { int a; int b; };\n"
4345 " } s;\n"
4346 " s.a = 4;\n"
4347 "}\n",
4348 declRefExpr(to(decl(hasAncestor(decl()))))));
4349}
4350
Nico Weberc0973372016-02-01 22:31:51 +00004351TEST(HasAncestor, NonParmDependentTemplateParmVarDeclRefExpr) {
4352 EXPECT_TRUE(matches("struct PartitionAllocator {\n"
4353 " template<typename T>\n"
4354 " static int quantizedSize(int count) {\n"
4355 " return count;\n"
4356 " }\n"
4357 " void f() { quantizedSize<int>(10); }\n"
4358 "};",
4359 declRefExpr(to(decl(hasAncestor(decl()))))));
4360}
4361
Nico Weber26911c72016-02-08 22:23:09 +00004362TEST(HasAncestor, AddressOfExplicitSpecializationFunction) {
4363 EXPECT_TRUE(matches("template <class T> void f();\n"
4364 "template <> void f<int>();\n"
4365 "void (*get_f())() { return f<int>; }\n",
4366 declRefExpr(to(decl(hasAncestor(decl()))))));
4367}
4368
Manuel Klimekc844a462012-12-06 14:42:48 +00004369TEST(HasParent, MatchesAllParents) {
4370 EXPECT_TRUE(matches(
4371 "template <typename T> struct C { static void f() { 42; } };"
4372 "void t() { C<int>::f(); }",
4373 integerLiteral(
4374 equals(42),
4375 hasParent(compoundStmt(hasParent(functionDecl(
Aaron Ballman512fb642015-09-17 13:30:52 +00004376 hasParent(cxxRecordDecl(isTemplateInstantiation())))))))));
4377 EXPECT_TRUE(
4378 matches("template <typename T> struct C { static void f() { 42; } };"
4379 "void t() { C<int>::f(); }",
4380 integerLiteral(
4381 equals(42),
4382 hasParent(compoundStmt(hasParent(functionDecl(hasParent(
4383 cxxRecordDecl(unless(isTemplateInstantiation()))))))))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004384 EXPECT_TRUE(matches(
4385 "template <typename T> struct C { static void f() { 42; } };"
4386 "void t() { C<int>::f(); }",
4387 integerLiteral(equals(42),
Aaron Ballman512fb642015-09-17 13:30:52 +00004388 hasParent(compoundStmt(
4389 allOf(hasParent(functionDecl(hasParent(
4390 cxxRecordDecl(isTemplateInstantiation())))),
4391 hasParent(functionDecl(hasParent(cxxRecordDecl(
4392 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00004393 EXPECT_TRUE(
4394 notMatches("template <typename T> struct C { static void f() {} };"
4395 "void t() { C<int>::f(); }",
4396 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00004397}
4398
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00004399TEST(HasParent, NoDuplicateParents) {
4400 class HasDuplicateParents : public BoundNodesCallback {
4401 public:
4402 bool run(const BoundNodes *Nodes) override { return false; }
4403 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
4404 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
4405 std::set<const void *> Parents;
4406 for (const auto &Parent : Context->getParents(*Node)) {
4407 if (!Parents.insert(Parent.getMemoizationData()).second) {
4408 return true;
4409 }
4410 }
4411 return false;
4412 }
4413 };
4414 EXPECT_FALSE(matchAndVerifyResultTrue(
4415 "template <typename T> int Foo() { return 1 + 2; }\n"
4416 "int x = Foo<int>() + Foo<unsigned>();",
4417 stmt().bind("node"), new HasDuplicateParents()));
4418}
4419
Daniel Jasper516b02e2012-10-17 08:52:59 +00004420TEST(TypeMatching, MatchesTypes) {
4421 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
4422}
4423
Samuel Benzaquenbd3232a2015-12-22 20:06:40 +00004424TEST(TypeMatching, MatchesBool) {
4425 EXPECT_TRUE(matches("struct S { bool func(); };",
4426 cxxMethodDecl(returns(booleanType()))));
4427 EXPECT_TRUE(notMatches("struct S { void func(); };",
4428 cxxMethodDecl(returns(booleanType()))));
4429}
4430
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004431TEST(TypeMatching, MatchesVoid) {
Aaron Ballman512fb642015-09-17 13:30:52 +00004432 EXPECT_TRUE(matches("struct S { void func(); };",
4433 cxxMethodDecl(returns(voidType()))));
Samuel Benzaquenb405c082014-12-15 15:09:22 +00004434}
4435
Aaron Ballmaneb7e5d92016-02-18 16:36:01 +00004436TEST(TypeMatching, MatchesRealFloats) {
4437 EXPECT_TRUE(matches("struct S { float func(); };",
4438 cxxMethodDecl(returns(realFloatingPointType()))));
4439 EXPECT_TRUE(notMatches("struct S { int func(); };",
4440 cxxMethodDecl(returns(realFloatingPointType()))));
4441 EXPECT_TRUE(matches("struct S { long double func(); };",
4442 cxxMethodDecl(returns(realFloatingPointType()))));
4443}
4444
Daniel Jasper516b02e2012-10-17 08:52:59 +00004445TEST(TypeMatching, MatchesArrayTypes) {
4446 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
4447 EXPECT_TRUE(matches("int a[42];", arrayType()));
4448 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
4449
4450 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
4451 arrayType(hasElementType(builtinType()))));
4452
4453 EXPECT_TRUE(matches(
4454 "int const a[] = { 2, 3 };",
4455 qualType(arrayType(hasElementType(builtinType())))));
4456 EXPECT_TRUE(matches(
4457 "int const a[] = { 2, 3 };",
4458 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4459 EXPECT_TRUE(matches(
4460 "typedef const int T; T x[] = { 1, 2 };",
4461 qualType(isConstQualified(), arrayType())));
4462
4463 EXPECT_TRUE(notMatches(
4464 "int a[] = { 2, 3 };",
4465 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
4466 EXPECT_TRUE(notMatches(
4467 "int a[] = { 2, 3 };",
4468 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
4469 EXPECT_TRUE(notMatches(
4470 "int const a[] = { 2, 3 };",
4471 qualType(arrayType(hasElementType(builtinType())),
4472 unless(isConstQualified()))));
4473
4474 EXPECT_TRUE(matches("int a[2];",
4475 constantArrayType(hasElementType(builtinType()))));
4476 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
4477}
4478
Matthias Gehre2cf7e802015-10-12 21:46:07 +00004479TEST(TypeMatching, DecayedType) {
4480 EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
4481 EXPECT_TRUE(notMatches("int i[7];", decayedType()));
4482}
4483
Daniel Jasper516b02e2012-10-17 08:52:59 +00004484TEST(TypeMatching, MatchesComplexTypes) {
4485 EXPECT_TRUE(matches("_Complex float f;", complexType()));
4486 EXPECT_TRUE(matches(
4487 "_Complex float f;",
4488 complexType(hasElementType(builtinType()))));
4489 EXPECT_TRUE(notMatches(
4490 "_Complex float f;",
4491 complexType(hasElementType(isInteger()))));
4492}
4493
4494TEST(TypeMatching, MatchesConstantArrayTypes) {
4495 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
4496 EXPECT_TRUE(notMatches(
4497 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
4498 constantArrayType(hasElementType(builtinType()))));
4499
4500 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
4501 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
4502 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
4503}
4504
4505TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
4506 EXPECT_TRUE(matches(
4507 "template <typename T, int Size> class array { T data[Size]; };",
4508 dependentSizedArrayType()));
4509 EXPECT_TRUE(notMatches(
4510 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
4511 dependentSizedArrayType()));
4512}
4513
4514TEST(TypeMatching, MatchesIncompleteArrayType) {
4515 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
4516 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
4517
4518 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
4519 incompleteArrayType()));
4520}
4521
4522TEST(TypeMatching, MatchesVariableArrayType) {
4523 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
4524 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
4525
4526 EXPECT_TRUE(matches(
4527 "void f(int b) { int a[b]; }",
4528 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4529 varDecl(hasName("b")))))))));
4530}
4531
4532TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00004533 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
4534 llvm::Triple::Win32) {
4535 // FIXME: Make this work for MSVC.
4536 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004537
David Majnemer197e2102014-03-05 06:32:38 +00004538 EXPECT_TRUE(matches("_Atomic(int) i;",
4539 atomicType(hasValueType(isInteger()))));
4540 EXPECT_TRUE(notMatches("_Atomic(float) f;",
4541 atomicType(hasValueType(isInteger()))));
4542 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00004543}
4544
4545TEST(TypeMatching, MatchesAutoTypes) {
4546 EXPECT_TRUE(matches("auto i = 2;", autoType()));
4547 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
4548 autoType()));
4549
Richard Smith061f1e22013-04-30 21:23:01 +00004550 // FIXME: Matching against the type-as-written can't work here, because the
4551 // type as written was not deduced.
4552 //EXPECT_TRUE(matches("auto a = 1;",
4553 // autoType(hasDeducedType(isInteger()))));
4554 //EXPECT_TRUE(notMatches("auto b = 2.0;",
4555 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004556}
4557
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00004558TEST(TypeMatching, MatchesFunctionTypes) {
4559 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
4560 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
4561}
4562
Aaron Ballman7e7b7b22016-02-01 14:11:47 +00004563TEST(TypeMatching, MatchesFunctionProtoTypes) {
4564 EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
4565 EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
4566 EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
4567 EXPECT_TRUE(notMatchesC("void f();", functionProtoType()));
4568 EXPECT_TRUE(
4569 matchesC("void f(void);", functionProtoType(parameterCountIs(0))));
4570}
4571
Edwin Vaneec074802013-04-01 18:33:34 +00004572TEST(TypeMatching, MatchesParenType) {
4573 EXPECT_TRUE(
4574 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
4575 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
4576
4577 EXPECT_TRUE(matches(
4578 "int (*ptr_to_func)(int);",
4579 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4580 EXPECT_TRUE(notMatches(
4581 "int (*ptr_to_array)[4];",
4582 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4583}
4584
Daniel Jasper516b02e2012-10-17 08:52:59 +00004585TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004586 // FIXME: Reactive when these tests can be more specific (not matching
4587 // implicit code on certain platforms), likely when we have hasDescendant for
4588 // Types/TypeLocs.
4589 //EXPECT_TRUE(matchAndVerifyResultTrue(
4590 // "int* a;",
4591 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4592 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4593 //EXPECT_TRUE(matchAndVerifyResultTrue(
4594 // "int* a;",
4595 // pointerTypeLoc().bind("loc"),
4596 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004597 EXPECT_TRUE(matches(
4598 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004599 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004600 EXPECT_TRUE(matches(
4601 "int** a;",
4602 loc(pointerType(pointee(pointerType())))));
4603 EXPECT_TRUE(matches(
4604 "int* b; int* * const a = &b;",
4605 loc(qualType(isConstQualified(), pointerType()))));
4606
4607 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004608 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4609 hasType(blockPointerType()))));
4610 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4611 hasType(memberPointerType()))));
4612 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4613 hasType(pointerType()))));
4614 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4615 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004616 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4617 hasType(lValueReferenceType()))));
4618 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4619 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004620
Daniel Jasper7943eb52012-10-17 13:35:36 +00004621 Fragment = "int *ptr;";
4622 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4623 hasType(blockPointerType()))));
4624 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4625 hasType(memberPointerType()))));
4626 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4627 hasType(pointerType()))));
4628 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4629 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004630
Daniel Jasper7943eb52012-10-17 13:35:36 +00004631 Fragment = "int a; int &ref = a;";
4632 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4633 hasType(blockPointerType()))));
4634 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4635 hasType(memberPointerType()))));
4636 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4637 hasType(pointerType()))));
4638 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4639 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004640 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4641 hasType(lValueReferenceType()))));
4642 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4643 hasType(rValueReferenceType()))));
4644
4645 Fragment = "int &&ref = 2;";
4646 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4647 hasType(blockPointerType()))));
4648 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4649 hasType(memberPointerType()))));
4650 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4651 hasType(pointerType()))));
4652 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4653 hasType(referenceType()))));
4654 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4655 hasType(lValueReferenceType()))));
4656 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4657 hasType(rValueReferenceType()))));
4658}
4659
4660TEST(TypeMatching, AutoRefTypes) {
4661 std::string Fragment = "auto a = 1;"
4662 "auto b = a;"
4663 "auto &c = a;"
4664 "auto &&d = c;"
4665 "auto &&e = 2;";
4666 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4667 hasType(referenceType()))));
4668 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4669 hasType(referenceType()))));
4670 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4671 hasType(referenceType()))));
4672 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4673 hasType(lValueReferenceType()))));
4674 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4675 hasType(rValueReferenceType()))));
4676 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4677 hasType(referenceType()))));
4678 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4679 hasType(lValueReferenceType()))));
4680 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4681 hasType(rValueReferenceType()))));
4682 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4683 hasType(referenceType()))));
4684 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4685 hasType(lValueReferenceType()))));
4686 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4687 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004688}
4689
4690TEST(TypeMatching, PointeeTypes) {
4691 EXPECT_TRUE(matches("int b; int &a = b;",
4692 referenceType(pointee(builtinType()))));
4693 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4694
4695 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004696 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004697
4698 EXPECT_TRUE(matches(
4699 "int const *A;",
4700 pointerType(pointee(isConstQualified(), builtinType()))));
4701 EXPECT_TRUE(notMatches(
4702 "int *A;",
4703 pointerType(pointee(isConstQualified(), builtinType()))));
4704}
4705
4706TEST(TypeMatching, MatchesPointersToConstTypes) {
4707 EXPECT_TRUE(matches("int b; int * const a = &b;",
4708 loc(pointerType())));
4709 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004710 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004711 EXPECT_TRUE(matches(
4712 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004713 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004714 EXPECT_TRUE(matches(
4715 "int b; const int * a = &b;",
4716 pointerType(pointee(builtinType()))));
4717}
4718
4719TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004720 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4721 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004722}
4723
Edwin Vanef901b712013-02-25 14:49:29 +00004724TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004725 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004726 templateSpecializationType()));
4727}
4728
Edwin Vaneb6eae142013-02-25 20:43:32 +00004729TEST(TypeMatching, MatchesRecordType) {
4730 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004731 EXPECT_TRUE(matches("struct S{}; S s;",
4732 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4733 EXPECT_TRUE(notMatches("int i;",
4734 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004735}
4736
4737TEST(TypeMatching, MatchesElaboratedType) {
4738 EXPECT_TRUE(matches(
4739 "namespace N {"
4740 " namespace M {"
4741 " class D {};"
4742 " }"
4743 "}"
4744 "N::M::D d;", elaboratedType()));
4745 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4746 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4747}
4748
4749TEST(ElaboratedTypeNarrowing, hasQualifier) {
4750 EXPECT_TRUE(matches(
4751 "namespace N {"
4752 " namespace M {"
4753 " class D {};"
4754 " }"
4755 "}"
4756 "N::M::D d;",
4757 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4758 EXPECT_TRUE(notMatches(
4759 "namespace M {"
4760 " class D {};"
4761 "}"
4762 "M::D d;",
4763 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004764 EXPECT_TRUE(notMatches(
4765 "struct D {"
4766 "} d;",
4767 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004768}
4769
4770TEST(ElaboratedTypeNarrowing, namesType) {
4771 EXPECT_TRUE(matches(
4772 "namespace N {"
4773 " namespace M {"
4774 " class D {};"
4775 " }"
4776 "}"
4777 "N::M::D d;",
4778 elaboratedType(elaboratedType(namesType(recordType(
4779 hasDeclaration(namedDecl(hasName("D")))))))));
4780 EXPECT_TRUE(notMatches(
4781 "namespace M {"
4782 " class D {};"
4783 "}"
4784 "M::D d;",
4785 elaboratedType(elaboratedType(namesType(typedefType())))));
4786}
4787
Samuel Benzaquenf8ec4542015-08-26 16:15:59 +00004788TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
4789 const std::string code = "template <typename T>"
4790 "int F() {"
4791 " return 1 + T();"
4792 "}"
4793 "int i = F<int>();";
4794 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
4795 expr(hasType(substTemplateTypeParmType()))))));
4796 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
4797 expr(hasType(substTemplateTypeParmType()))))));
4798}
4799
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004800TEST(NNS, MatchesNestedNameSpecifiers) {
4801 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4802 nestedNameSpecifier()));
4803 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4804 nestedNameSpecifier()));
4805 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4806 nestedNameSpecifier()));
Daniel Jasperc8f472c2015-12-02 13:57:46 +00004807 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
4808 nestedNameSpecifier()));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004809
4810 EXPECT_TRUE(matches(
4811 "struct A { static void f() {} }; void g() { A::f(); }",
4812 nestedNameSpecifier()));
4813 EXPECT_TRUE(notMatches(
4814 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4815 nestedNameSpecifier()));
4816}
4817
Daniel Jasper87c3d362012-09-20 14:12:57 +00004818TEST(NullStatement, SimpleCases) {
4819 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4820 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4821}
4822
Aaron Ballman11825f22015-08-18 19:55:20 +00004823TEST(NS, Anonymous) {
4824 EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
4825 EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
4826}
4827
Aaron Ballman6c79f352015-08-28 19:39:21 +00004828TEST(NS, Alias) {
4829 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
4830 namespaceAliasDecl(hasName("alias"))));
4831}
4832
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004833TEST(NNS, MatchesTypes) {
4834 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4835 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4836 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4837 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4838 Matcher));
4839 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4840}
4841
4842TEST(NNS, MatchesNamespaceDecls) {
4843 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4844 specifiesNamespace(hasName("ns")));
4845 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4846 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4847 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4848}
4849
4850TEST(NNS, BindsNestedNameSpecifiers) {
4851 EXPECT_TRUE(matchAndVerifyResultTrue(
4852 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4853 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4854 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4855}
4856
4857TEST(NNS, BindsNestedNameSpecifierLocs) {
4858 EXPECT_TRUE(matchAndVerifyResultTrue(
4859 "namespace ns { struct B {}; } ns::B b;",
4860 loc(nestedNameSpecifier()).bind("loc"),
4861 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4862}
4863
4864TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4865 EXPECT_TRUE(matches(
4866 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4867 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4868 EXPECT_TRUE(matches(
4869 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004870 nestedNameSpecifierLoc(hasPrefix(
4871 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004872}
4873
Daniel Jasper6fc34332012-10-30 15:42:00 +00004874TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4875 std::string Fragment =
4876 "namespace a { struct A { struct B { struct C {}; }; }; };"
4877 "void f() { a::A::B::C c; }";
4878 EXPECT_TRUE(matches(
4879 Fragment,
4880 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4881 hasDescendant(nestedNameSpecifier(
4882 specifiesNamespace(hasName("a")))))));
4883 EXPECT_TRUE(notMatches(
4884 Fragment,
4885 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4886 has(nestedNameSpecifier(
4887 specifiesNamespace(hasName("a")))))));
4888 EXPECT_TRUE(matches(
4889 Fragment,
4890 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4891 has(nestedNameSpecifier(
4892 specifiesNamespace(hasName("a")))))));
4893
4894 // Not really useful because a NestedNameSpecifier can af at most one child,
4895 // but to complete the interface.
4896 EXPECT_TRUE(matchAndVerifyResultTrue(
4897 Fragment,
4898 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4899 forEach(nestedNameSpecifier().bind("x"))),
4900 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4901}
4902
4903TEST(NNS, NestedNameSpecifiersAsDescendants) {
4904 std::string Fragment =
4905 "namespace a { struct A { struct B { struct C {}; }; }; };"
4906 "void f() { a::A::B::C c; }";
4907 EXPECT_TRUE(matches(
4908 Fragment,
4909 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4910 asString("struct a::A")))))));
4911 EXPECT_TRUE(matchAndVerifyResultTrue(
4912 Fragment,
4913 functionDecl(hasName("f"),
4914 forEachDescendant(nestedNameSpecifier().bind("x"))),
4915 // Nested names: a, a::A and a::A::B.
4916 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4917}
4918
4919TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4920 std::string Fragment =
4921 "namespace a { struct A { struct B { struct C {}; }; }; };"
4922 "void f() { a::A::B::C c; }";
4923 EXPECT_TRUE(matches(
4924 Fragment,
4925 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4926 hasDescendant(loc(nestedNameSpecifier(
4927 specifiesNamespace(hasName("a"))))))));
4928 EXPECT_TRUE(notMatches(
4929 Fragment,
4930 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4931 has(loc(nestedNameSpecifier(
4932 specifiesNamespace(hasName("a"))))))));
4933 EXPECT_TRUE(matches(
4934 Fragment,
4935 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4936 has(loc(nestedNameSpecifier(
4937 specifiesNamespace(hasName("a"))))))));
4938
4939 EXPECT_TRUE(matchAndVerifyResultTrue(
4940 Fragment,
4941 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4942 forEach(nestedNameSpecifierLoc().bind("x"))),
4943 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4944}
4945
4946TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4947 std::string Fragment =
4948 "namespace a { struct A { struct B { struct C {}; }; }; };"
4949 "void f() { a::A::B::C c; }";
4950 EXPECT_TRUE(matches(
4951 Fragment,
4952 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4953 asString("struct a::A"))))))));
4954 EXPECT_TRUE(matchAndVerifyResultTrue(
4955 Fragment,
4956 functionDecl(hasName("f"),
4957 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4958 // Nested names: a, a::A and a::A::B.
4959 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4960}
4961
Manuel Klimek191c0932013-02-01 13:41:35 +00004962template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004963public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004964 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4965 StringRef InnerId)
4966 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004967 }
4968
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004969 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimek191c0932013-02-01 13:41:35 +00004970
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004971 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekc2687452012-10-24 14:47:44 +00004972 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004973 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4974 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004975 }
4976private:
4977 std::string Id;
4978 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004979 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004980};
4981
4982TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004983 EXPECT_TRUE(matchAndVerifyResultTrue(
4984 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4985 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004986 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4987 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004988 EXPECT_TRUE(matchAndVerifyResultFalse(
4989 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4990 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004991 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4992 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004993}
4994
4995TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004996 EXPECT_TRUE(matchAndVerifyResultTrue(
4997 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004998 new VerifyMatchOnNode<clang::Stmt>(
4999 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00005000 EXPECT_TRUE(matchAndVerifyResultFalse(
5001 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00005002 new VerifyMatchOnNode<clang::Stmt>(
5003 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00005004}
5005
5006TEST(MatchFinder, CanMatchSingleNodesRecursively) {
5007 EXPECT_TRUE(matchAndVerifyResultTrue(
5008 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
5009 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00005010 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00005011 EXPECT_TRUE(matchAndVerifyResultFalse(
5012 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
5013 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00005014 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00005015}
5016
Manuel Klimekbee08572013-02-07 12:42:10 +00005017template <typename T>
5018class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
5019public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005020 bool run(const BoundNodes *Nodes) override { return false; }
Manuel Klimekbee08572013-02-07 12:42:10 +00005021
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005022 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Manuel Klimekbee08572013-02-07 12:42:10 +00005023 const T *Node = Nodes->getNodeAs<T>("");
5024 return verify(*Nodes, *Context, Node);
5025 }
5026
5027 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00005028 // Use the original typed pointer to verify we can pass pointers to subtypes
5029 // to equalsNode.
5030 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00005031 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00005032 "", match(stmt(hasParent(
5033 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00005034 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00005035 }
5036 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00005037 // Use the original typed pointer to verify we can pass pointers to subtypes
5038 // to equalsNode.
5039 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00005040 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00005041 "", match(decl(hasParent(
5042 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00005043 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00005044 }
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00005045 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
5046 // Use the original typed pointer to verify we can pass pointers to subtypes
5047 // to equalsNode.
5048 const T *TypedNode = cast<T>(Node);
5049 const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
5050 return selectFirst<T>(
5051 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
5052 hasType(type(equalsNode(TypedNode)).bind(""))))))),
5053 *Dec, Context)) != nullptr;
5054 }
Manuel Klimekbee08572013-02-07 12:42:10 +00005055};
5056
5057TEST(IsEqualTo, MatchesNodesByIdentity) {
5058 EXPECT_TRUE(matchAndVerifyResultTrue(
5059 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00005060 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
5061 EXPECT_TRUE(matchAndVerifyResultTrue(
5062 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
5063 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Angel Garcia Gomez4647ed72015-10-30 09:35:51 +00005064 EXPECT_TRUE(matchAndVerifyResultTrue(
5065 "class X { class Y {} y; };",
5066 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
5067 new VerifyAncestorHasChildIsEqual<Type>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00005068}
5069
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00005070TEST(MatchFinder, CheckProfiling) {
5071 MatchFinder::MatchFinderOptions Options;
5072 llvm::StringMap<llvm::TimeRecord> Records;
5073 Options.CheckProfiling.emplace(Records);
5074 MatchFinder Finder(std::move(Options));
5075
5076 struct NamedCallback : public MatchFinder::MatchCallback {
5077 void run(const MatchFinder::MatchResult &Result) override {}
5078 StringRef getID() const override { return "MyID"; }
5079 } Callback;
5080 Finder.addMatcher(decl(), &Callback);
5081 std::unique_ptr<FrontendActionFactory> Factory(
5082 newFrontendActionFactory(&Finder));
5083 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
5084
5085 EXPECT_EQ(1u, Records.size());
5086 EXPECT_EQ("MyID", Records.begin()->getKey());
5087}
5088
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00005089class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
5090public:
5091 VerifyStartOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005092 void run(const MatchFinder::MatchResult &Result) override {
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00005093 EXPECT_TRUE(Called);
5094 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005095 void onStartOfTranslationUnit() override { Called = true; }
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00005096 bool Called;
5097};
5098
5099TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
5100 MatchFinder Finder;
5101 VerifyStartOfTranslationUnit VerifyCallback;
5102 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00005103 std::unique_ptr<FrontendActionFactory> Factory(
5104 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00005105 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
5106 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00005107
5108 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00005109 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00005110 ASSERT_TRUE(AST.get());
5111 Finder.matchAST(AST->getASTContext());
5112 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00005113}
5114
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00005115class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
5116public:
5117 VerifyEndOfTranslationUnit() : Called(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005118 void run(const MatchFinder::MatchResult &Result) override {
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00005119 EXPECT_FALSE(Called);
5120 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005121 void onEndOfTranslationUnit() override { Called = true; }
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00005122 bool Called;
5123};
5124
5125TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
5126 MatchFinder Finder;
5127 VerifyEndOfTranslationUnit VerifyCallback;
5128 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00005129 std::unique_ptr<FrontendActionFactory> Factory(
5130 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00005131 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
5132 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00005133
5134 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00005135 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00005136 ASSERT_TRUE(AST.get());
5137 Finder.matchAST(AST->getASTContext());
5138 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00005139}
5140
Daniel Jasper739ae642016-02-03 14:29:55 +00005141TEST(Matcher, matchOverEntireASTContext) {
5142 std::unique_ptr<ASTUnit> AST =
5143 clang::tooling::buildASTFromCode("struct { int *foo; };");
5144 ASSERT_TRUE(AST.get());
5145 auto PT = selectFirst<PointerType>(
5146 "x", match(pointerType().bind("x"), AST->getASTContext()));
5147 EXPECT_NE(nullptr, PT);
5148}
5149
Manuel Klimekbbb75852013-06-20 14:06:32 +00005150TEST(EqualsBoundNodeMatcher, QualType) {
5151 EXPECT_TRUE(matches(
5152 "int i = 1;", varDecl(hasType(qualType().bind("type")),
5153 hasInitializer(ignoringParenImpCasts(
5154 hasType(qualType(equalsBoundNode("type"))))))));
5155 EXPECT_TRUE(notMatches("int i = 1.f;",
5156 varDecl(hasType(qualType().bind("type")),
5157 hasInitializer(ignoringParenImpCasts(hasType(
5158 qualType(equalsBoundNode("type"))))))));
5159}
5160
5161TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
5162 EXPECT_TRUE(notMatches(
5163 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
5164 hasInitializer(ignoringParenImpCasts(
5165 hasType(qualType(equalsBoundNode("type"))))))));
5166}
5167
5168TEST(EqualsBoundNodeMatcher, Stmt) {
5169 EXPECT_TRUE(
5170 matches("void f() { if(true) {} }",
5171 stmt(allOf(ifStmt().bind("if"),
5172 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
5173
5174 EXPECT_TRUE(notMatches(
5175 "void f() { if(true) { if (true) {} } }",
5176 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
5177}
5178
5179TEST(EqualsBoundNodeMatcher, Decl) {
5180 EXPECT_TRUE(matches(
5181 "class X { class Y {}; };",
5182 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
5183 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
5184
5185 EXPECT_TRUE(notMatches("class X { class Y {}; };",
5186 decl(allOf(recordDecl(hasName("::X")).bind("record"),
5187 has(decl(equalsBoundNode("record")))))));
5188}
5189
5190TEST(EqualsBoundNodeMatcher, Type) {
5191 EXPECT_TRUE(matches(
5192 "class X { int a; int b; };",
5193 recordDecl(
5194 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5195 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
5196
5197 EXPECT_TRUE(notMatches(
5198 "class X { int a; double b; };",
5199 recordDecl(
5200 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5201 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
5202}
5203
5204TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00005205 EXPECT_TRUE(matchAndVerifyResultTrue(
5206 "int f() {"
5207 " if (1) {"
5208 " int i = 9;"
5209 " }"
5210 " int j = 10;"
5211 " {"
5212 " float k = 9.0;"
5213 " }"
5214 " return 0;"
5215 "}",
5216 // Look for variable declarations within functions whose type is the same
5217 // as the function return type.
5218 functionDecl(returns(qualType().bind("type")),
5219 forEachDescendant(varDecl(hasType(
5220 qualType(equalsBoundNode("type")))).bind("decl"))),
5221 // Only i and j should match, not k.
5222 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
5223}
5224
5225TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
5226 EXPECT_TRUE(matchAndVerifyResultTrue(
5227 "void f() {"
5228 " int x;"
5229 " double d;"
5230 " x = d + x - d + x;"
5231 "}",
5232 functionDecl(
5233 hasName("f"), forEachDescendant(varDecl().bind("d")),
5234 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
5235 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
5236}
5237
Manuel Klimekce68f772014-03-25 14:39:26 +00005238TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
5239 EXPECT_TRUE(matchAndVerifyResultTrue(
5240 "struct StringRef { int size() const; const char* data() const; };"
5241 "void f(StringRef v) {"
5242 " v.data();"
5243 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00005244 cxxMemberCallExpr(
5245 callee(cxxMethodDecl(hasName("data"))),
5246 on(declRefExpr(to(
5247 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
5248 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
5249 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
Manuel Klimekce68f772014-03-25 14:39:26 +00005250 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
5251 .bind("data"),
5252 new VerifyIdIsBoundTo<Expr>("data", 1)));
5253
5254 EXPECT_FALSE(matches(
5255 "struct StringRef { int size() const; const char* data() const; };"
5256 "void f(StringRef v) {"
5257 " v.data();"
5258 " v.size();"
5259 "}",
Aaron Ballman512fb642015-09-17 13:30:52 +00005260 cxxMemberCallExpr(
5261 callee(cxxMethodDecl(hasName("data"))),
5262 on(declRefExpr(to(
5263 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
5264 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
5265 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
Manuel Klimekce68f772014-03-25 14:39:26 +00005266 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
5267 .bind("data")));
5268}
5269
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00005270TEST(TypeDefDeclMatcher, Match) {
5271 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
5272 typedefDecl(hasName("typedefDeclTest"))));
5273}
5274
Aaron Ballman11825f22015-08-18 19:55:20 +00005275TEST(IsInlineMatcher, IsInline) {
5276 EXPECT_TRUE(matches("void g(); inline void f();",
5277 functionDecl(isInline(), hasName("f"))));
5278 EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
5279 namespaceDecl(isInline(), hasName("m"))));
5280}
5281
Aaron Ballman7e7b7b22016-02-01 14:11:47 +00005282// FIXME: Figure out how to specify paths so the following tests pass on
5283// Windows.
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00005284#ifndef LLVM_ON_WIN32
5285
5286TEST(Matcher, IsExpansionInMainFileMatcher) {
5287 EXPECT_TRUE(matches("class X {};",
5288 recordDecl(hasName("X"), isExpansionInMainFile())));
5289 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
5290 FileContentMappings M;
5291 M.push_back(std::make_pair("/other", "class X {};"));
5292 EXPECT_TRUE(matchesConditionally("#include <other>\n",
5293 recordDecl(isExpansionInMainFile()), false,
5294 "-isystem/", M));
5295}
5296
5297TEST(Matcher, IsExpansionInSystemHeader) {
5298 FileContentMappings M;
5299 M.push_back(std::make_pair("/other", "class X {};"));
5300 EXPECT_TRUE(matchesConditionally(
5301 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
5302 "-isystem/", M));
5303 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
5304 recordDecl(isExpansionInSystemHeader()),
5305 false, "-I/", M));
5306 EXPECT_TRUE(notMatches("class X {};",
5307 recordDecl(isExpansionInSystemHeader())));
5308 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
5309}
5310
5311TEST(Matcher, IsExpansionInFileMatching) {
5312 FileContentMappings M;
5313 M.push_back(std::make_pair("/foo", "class A {};"));
5314 M.push_back(std::make_pair("/bar", "class B {};"));
5315 EXPECT_TRUE(matchesConditionally(
5316 "#include <foo>\n"
5317 "#include <bar>\n"
5318 "class X {};",
5319 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
5320 "-isystem/", M));
5321 EXPECT_TRUE(matchesConditionally(
5322 "#include <foo>\n"
5323 "#include <bar>\n"
5324 "class X {};",
5325 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
5326 "-isystem/", M));
5327}
5328
5329#endif // LLVM_ON_WIN32
5330
Manuel Klimekbfa43572015-03-12 15:48:15 +00005331
5332TEST(ObjCMessageExprMatcher, SimpleExprs) {
5333 // don't find ObjCMessageExpr where none are present
5334 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
5335
5336 std::string Objc1String =
5337 "@interface Str "
5338 " - (Str *)uppercaseString:(Str *)str;"
5339 "@end "
5340 "@interface foo "
5341 "- (void)meth:(Str *)text;"
5342 "@end "
5343 " "
5344 "@implementation foo "
5345 "- (void) meth:(Str *)text { "
5346 " [self contents];"
5347 " Str *up = [text uppercaseString];"
5348 "} "
5349 "@end ";
5350 EXPECT_TRUE(matchesObjC(
5351 Objc1String,
5352 objcMessageExpr(anything())));
5353 EXPECT_TRUE(matchesObjC(
5354 Objc1String,
5355 objcMessageExpr(hasSelector("contents"))));
5356 EXPECT_TRUE(matchesObjC(
5357 Objc1String,
5358 objcMessageExpr(matchesSelector("cont*"))));
5359 EXPECT_FALSE(matchesObjC(
5360 Objc1String,
5361 objcMessageExpr(matchesSelector("?cont*"))));
5362 EXPECT_TRUE(notMatchesObjC(
5363 Objc1String,
5364 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
5365 EXPECT_TRUE(matchesObjC(
5366 Objc1String,
5367 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
5368 EXPECT_TRUE(matchesObjC(
5369 Objc1String,
Manuel Klimeke67a9d62015-09-08 10:11:26 +00005370 objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
5371 EXPECT_TRUE(matchesObjC(
5372 Objc1String,
Manuel Klimekbfa43572015-03-12 15:48:15 +00005373 objcMessageExpr(matchesSelector("uppercase*"),
5374 argumentCountIs(0)
5375 )));
Manuel Klimekbfa43572015-03-12 15:48:15 +00005376}
5377
Aaron Ballman232e63d2016-02-16 21:02:23 +00005378TEST(NullPointerConstants, Basic) {
5379 EXPECT_TRUE(matches("#define NULL ((void *)0)\n"
5380 "void *v1 = NULL;", expr(nullPointerConstant())));
5381 EXPECT_TRUE(matches("void *v2 = nullptr;", expr(nullPointerConstant())));
5382 EXPECT_TRUE(matches("void *v3 = __null;", expr(nullPointerConstant())));
5383 EXPECT_TRUE(matches("char *cp = (char *)0;", expr(nullPointerConstant())));
5384 EXPECT_TRUE(matches("int *ip = 0;", expr(nullPointerConstant())));
Aaron Ballmancc928c82016-02-16 21:06:10 +00005385 EXPECT_TRUE(notMatches("int i = 0;", expr(nullPointerConstant())));
Aaron Ballman232e63d2016-02-16 21:02:23 +00005386}
5387
Manuel Klimek04616e42012-07-06 05:48:52 +00005388} // end namespace ast_matchers
5389} // end namespace clang